I have a Http request which give me the following Json that save in an observable
{
"proyecto":{
"nombre": "Mercado de Ideas",
"tecnologias": [
{
"nombre": ".NET",
"icono": "http://getsetwebsite.com/wp-content/uploads/2016/07/net.png"
},
{
"nombre": "Angular",
"icono": "http://fourcast.io/wp-content/uploads/2016/10/angular.png"
}
],
"tiempo_restante": 80,
"alcance_restante": 90,
"recursos_devengados": 22
}
}
and save the observable with the following code
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { KpisProvider } from '../../providers/kpis/kpis';
/**
* Generated class for the ProyectoDetailsPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#Component({
selector: 'page-proyecto-details',
templateUrl: 'proyecto-details.html',
})
export class ProyectoDetailsPage {
public projectID: number;
public project : Observable<any>;
constructor(
public navCtrl : NavController,
public navParams: NavParams,
public kpis : KpisProvider
) {
this.projectID = this.navParams.get("projectID");
console.log(this.projectID)
}
ionViewDidLoad() {
console.log('ionViewDidLoad ProyectoDetailsPage');
this.project = this.kpis.getUserDetails(this.projectID);
console.log(this.project);
}
}
How to get the parameters, for example the "nombre" or "tiempo_restante" in the html? and obtain something like that
You have to subscribe to observable inorder to receive a data from it
this.kpis.getUserDetails(this.projectID).subscribe(
(data) => this.project = data
);
Html
{{project?.proyecto?.tiempo_restante}}
{{project?.proyecto?.nombre}}
Otherway you can implicitly subscribe to observable by using async pipe over the HTML.
<div *ngFor="let item in (project | async)?.proyecto.tecnologias">
{{item.nombre}}
{{item.icono}}
</div>
Related
I'm having trouble converting RSS to JSON using the rrs2json API with Ionic 3. If I execute the code it gives me the error --> Response {_body: "{" status ":" error "," message ":" rss_url parameter is required."} ", Status: 422, ok: false, statusText:" Unprocessable Entity "}
Code:
noticies.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RssProvider } from '../../providers/rss/rss';
#IonicPage()
#Component({
selector: 'page-noticies',
templateUrl: 'noticies.html',
})
export class NoticiesPage {
rssDataArray: any = [];
constructor(public navCtrl: NavController, public navParams: NavParams, public rssProvider: RssProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad NoticiesPage');
this.Get_RSS_Data()
}
Get_RSS_Data(){
this.rssProvider.GetRSS().subscribe(
data => {
this.rssDataArray = data;
console.log(data);
}
);
}
}
providers --> rss --> rss.ts
import { Injectable } from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class RssProvider {
constructor(public http: Http) {
console.log('Hello RssProvider Provider');
}
GetRSS(){
const RSS_URL: any='http://rss.cnn.com/rss/edition.rss';
const API: any='XXXXXXXXXXXXXX';
const count: any =20;
const API_URL: any ='https://api.rss2json.com/v1/api.json';
const response = this.http.post(API_URL, {'rss_url': RSS_URL,'api_key': API, 'count': count}).map(res => res.json());
return response;
}
}
Error -->
Error
Alright. I registered myself with the rss2json service and made sure this solution actually works (you can see the data in console).
The issue you have is that you are not using a proper way to form http request with HttpParams.
Here is working stackblitz that uses my key: https://stackblitz.com/edit/ionic-jdwqjg
now some details:
when you configure a URL using rss2json it basically adds parameters to the original URL, example:
https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Ftechcrunch.com%2Ffeed%2F&api_key=q5ijkolkdjk3urzrcfaehxeoimxr3tdu5ieiqcrq&order_by=pubDate&order_dir=asc&count=20
So in Angular/Ionic you need to leverage Angular's HttpParams to properly form request, here is your provider code with HttpParams:
provider code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable()
export class RssProvider {
private API_URL: string;
constructor(public http: HttpClient) {
this.API_URL = "https://api.rss2json.com/v1/api.json";
}
GetRSS() {
const params = { params: new HttpParams().set('rss_url', 'http://rss.cnn.com/rss/edition.rss').set('api_key','q5ijkolkdjk3urzrcfaehxeoimxr3tdu5ieiqcrq').set('order_by', 'pubDate').set('order_dir', 'asc')
}
return this.http.get(this.API_URL, params);
}
}
I have this JSON data and I'm getting it's output to a html file using angular. I use a service to get JSON data and a component to create the template. After using the template, I'm getting only id value and name value, but not url value.
JSON:
{
"A":1,
"B":[
{
"id":1,
"name":"One",
"url":"http://myapp/rootpath/first"
},
{
"id":2,
"name":"two",
"url":"http://myapp/rootpath/second"
}
]
}
I'm taking the JSON data to postArray variable in the component and pass it to the html file.
search.service.ts:
import { Injectable } from '#angular/core';
import {Http,Response} from "#angular/http";
import { Observable } from "rxjs";
import "rxjs/Rx";
import {JsoncallItem} from "./jsoncall-item";
#Injectable({
providedIn: 'root'
})
export class ApiService {
private postsURL ="http://myapp/items";
constructor(private http: Http ) {}
getPosts(): Observable<JsoncallItem[]>{
return this.http
.get(this.postsURL)
.map((response: Response)=> {
return <JsoncallItem[]>response.json();
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}
search.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiService } from "./../search.service";
import { JsoncallItem } from "./../jsoncall-item";
import { error } from 'util';
import { SearchtermPipe } from './../searchterm.pipe';
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
title = 'app';
_postsArray: JsoncallItem[];
constructor(private apiSerivce: ApiService){}
getPosts(): void {
this.apiSerivce.getPosts().
subscribe(
resultArray => this._postsArray = resultArray
)
//error => console.log("Error :: " + error ))
}
ngOnInit(): void{
this.getPosts();
}
}
search.component.html:
<div class="container">
<ul>
<li *ngFor="let post of _postsArray | searchterm: value">
{{post.id}}, {{post.name}}, {{post.url}}
<hr>
</li>
</ul>
</div>
Output shows the id and name of each data, but not showing the url. What could be the wrong here?
I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve. I was able to get JSON's data before but now that it's nested I don't know how to get it's data. This is what I've done so far
Service
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TestService {
url = "http://localhost:80/assets/data/test.json";
constructor(private http:Http) { }
getTestWithObservable(): Observable<any> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs';
import { TestService } from './test.service';
#Component({
selector: 'ngx-test',
styleUrls: ['./test.component.scss'],
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
let user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
JSON
[{
"id": 1,
"users": {
"user_id": 14,
"data": [{
"name": "James",
"age": 20
},
{
"name": "Damien",
"age": 25
}]
}
}]
HTML
<div *ngFor="let x of user_data; let i = index">
{{x.name}}
</div>
I'd appreciate if someone can point me out the solution or what I'm doing wrong.
You need to save the data in an instance property to access it. user_data is local to your function, you cannot access it in the template so you should use something like this :
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]['users'];
let user_data = user['data'];
console.log(user_data['name']);
this.user_data = user_data; // here
}
);
}
}
There is some problems with your code:
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) {
}
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
this.user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
In Angular >= 4, pipe methods is better to handle Observable
this.http.get(this.url)
.pipe(
filter(...),
map(...)
)
With HttpClient (Http is deprecated), the .json() is done for you. You don't need your extractData function.
You have to initialize your variable. And use "this" to refer to it.
I am developing the services of my application, but when I try to load the page it shows the following error:
Can't resolve all parameters for GameEditComponent: ([object Object],
[object Object], ?).
I tried in the service to put as an array or just leave any, but even then the error continued
game-edit.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs';
#Injectable()
export class GameEditService {
constructor(private http: Http) { }
getGame(id): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/game' + id).map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
getManufactures(): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/manufacture').map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
getPlatforms(): Observable<any> {
return this.http.get('http://localhost:8080/lightning/api/platform').map(res => res.json()).catch(error => {
throw new Error(error.message);
});
}
}
game-edit.component.ts
import { ActivatedRoute, Params } from '#angular/router';
import { Component, OnInit } from '#angular/core';
import { GameEditService } from './game-edit.service';
#Component({
moduleId: module.id,
selector: 'app-game-edit',
templateUrl: './game-edit.component.html',
styleUrls: ['./game-edit.component.css', '../styles.css' ]
})
export class GameEditComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute, private gameEditService: GameEditService, private id) {
this.gameEditService.getPlatforms().subscribe(platforms => {
console.log(platforms);
}), erro => console.log(erro);
this.gameEditService.getManufactures().subscribe(manufactures => {
console.log(manufactures);
}), erro => console.log(erro);
}
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.id = params['id'];
console.log(this.id);
});
this.gameEditService.getGame(this.id).subscribe(game => {
console.log(game);
}), erro => console.log(erro);
}
onSubmit(form){
console.log(form);
}
verificaValidTouched(campo){
return !campo.valid && campo.touched;
}
aplicaCssErro(campo){
return {
'subError': this.verificaValidTouched(campo)
}
}
}
This is the json that is coming, the first is for a selected game, the second is for the platforms and the third is for the manufacturers
json game selected
{
"id":1,
"name":"Street Fighter",
"category":"luta",
"price":20.5,
"quantity":1000,
"production":true,
"description":"descricao",
"image":"ps4.jpg",
"manufacture":
{
"id":1,
"name":"Sony",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
}
json platforms
{
"id":1,
"name":"PC",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
json manufactures
{
"id":1,
"name":"Sony",
"image":"ps4.jpg",
"imageFullPath":"http://localhost:8080/lightning/images/ps4.jpg"
}
Console
I'm using angular cli with with all packages in the most current versions.
I do not know if maybe this error is because of the platforms you have inside the game, or some other code problem, if you know something that could do to repair, I tried several solutions that I found through the internet, but none worked.
Thanks in advance.
The problem is the last argument in the component's constructor, private id. Angular will try to resolve this dependency, but can't find an injectable class for id. When looking at the code, I think there is no need to inject id into the constructor. Just define it as a property on your component:
// ... import statements
#Component({
moduleId: module.id,
selector: 'app-game-edit',
templateUrl: './game-edit.component.html',
styleUrls: ['./game-edit.component.css', '../styles.css' ]
})
export class GameEditComponent implements OnInit {
private id; // put the declaration of id here
// remove id declaration from the constructor, no need to inject it
constructor(private activatedRoute: ActivatedRoute,
private gameEditService: GameEditService) { // ...constructor code}
// other code
}
I solved it otherwise: My problem was that the HttpClient has a rare condition, it's not the same "import" line on the component that on the app.module...
On the Component is this:
import { HttpClient } from '#angular/common/http';
in app module is this:
import { HttpClientModule } from '#angular/common/http';
I'm trying to load a local JSON into my component, but I can't get the values from my service into my component. I can see the json data in the service but it is undefined in my component. Does anybody see what i'm doing wrong here ? Thanks.
Here is an SS of the console.log in both service and component
interfaces.json
{
"interfaces": {
"eth" : {"name" : "eth"},
"lte" : {"name" : "lte"},
"wlc" : {"name" : "wlc"},
"wlap" : {"name" : "wlap"}
}
}
interfaces.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
#Injectable()
export class Interfaces {
constructor(public http: Http) {};
public getData() {
return this.http.get('/assets/interfaces.json')
.map((res) => {res.json(); console.log(res); });
};
}
interfaces.component.ts
import { Component, OnInit } from '#angular/core';
import { Interfaces } from './interfaces.service';
import { Observable } from 'rxjs/Rx';
#Component({
selector: 'interfaces',
providers: [
Interfaces
],
template: `
<ul *dropdownMenu class="dropdown-menu" role="menu">
<li *ngFor="let interface of interfaces | async" role="menuitem">
<a [routerLink]=" ['./interfaces/eth'] "routerLinkActive="active"
[routerLinkActiveOptions]= "{exact: true}" class="dropdown-item" href="#">
{{interface.name}}Main Ethernet
</a>
</li>
</ul>
`,
})
export class InterfacesComponent implements OnInit {
constructor(public interfaces: Interfaces) {}
public ngOnInit() {
this.interfaces.getData().subscribe((data) => { this.data = data; console.log(data); });
}
}
The reason that it's undefined is that you are not returning your response inside the map not that map is not working..
.map((res) => {console.log(res); return res.json(); }); // missing return here
or without brackets:
.map((res) => res.json());
I don't know what is wrong as I'm new to angular2, but this works for me.
interfaces.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
#Injectable()
export class Interfaces {
constructor(public http: Http) {};
public getData() {
return this.http.get('/assets/interfaces.json');
}
}
interfaces.component.ts
import { Component, OnInit } from '#angular/core';
import { Interfaces } from './interfaces.service';
import { Observable } from 'rxjs/Rx';
export class InterfacesComponent implements OnInit {
constructor(public interfaces: Interfaces) {}
public ngOnInit() {
this.interfaces.getData().subscribe((data) => {
this.data = data;
console.log(data);
});
}
}