ngFor doesn't print JSON data - json

I'm developing an Angular2 application and I want to display some JSON data with http GET request from a JSON file.
Here's my JSON (file data/contatti.json):
[
"08823323459",
"3325849593",
"somemail#hotmail.com"
]
I have a ContactService that requests data from this file:
import { Injectable } from '#angular/core';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class ContattiService {
private contactUrl = 'data/contatti.json';
constructor(private http: Http) { }
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
getContatti(): Promise<string[]> {
return this.http.get(this.contactUrl)
.toPromise()
.then(res => res.json().data as string[])
.catch(this.handleError);
}
}
There is a component that retrieves the data using the service:
import { Component, OnInit } from '#angular/core'
import { ContattiService } from './contatti.service'
#Component({
selector: 'contact-app',
templateUrl: './contatti.html'
})
export class ContactComponent {
contatti: string[];
constructor(
private contactService: ContattiService) { }
ngOnInit(): void {
this.getContatti();
}
getContatti(): void {
this.contactService.getContatti().then(contatti => this.contatti = contatti);
}
}
But when I try to display them in my html page (contatti.html):
<div class="col-sm-6">
<div class="panel panel-default">
<ul>
<li *ngFor="let contatto of contatti">
{{contatto}}
</li>
</ul>
</div>
</div>
The page doesn't print data. Can someone help me please?

You should rewrite you method with subscribe:
getContatti(): void {
this.contactService.getContatti()
.subscribe(contatti => this.contatti = contatti);
}
and service to:
getContatti(): {
return this.http.get(this.contactUrl)
.map(res => res.json().data)
.catch(error => this.handleError(error));
}
And one more, if you try to access res.json().data your contatti.json should look like:
{
"data": [
"08823323459",
"3325849593",
"somemail#hotmail.com"
]
}

Try this inside the component,
getContatti(): void {
this.contactService.getContatti().subscribe(contatti=>{
this.contatti = contatti;
});
}
and service.ts should be,
getContatti(): {
return this.http.get(this.contactUrl)
.map(res => res.json().data)
.catch(error => this.handleError(error));
}

Related

How can I access the first element of JSON array data?

I'm using ionic as a front end and Laravel as a back end.
This is the returned JSON data from an API URL, I want to access just the first element which is a.jpg without anything else, I tried using filenames.[0] but it's just displaying [ which means that it's calling the first character not the first element of the array.
Here's the JSON data:
[{"filenames":"[\"a.jpg\",\"b.jpg\",\"c.jpg\"]"}]
Here's my .ts file
import { ApiLandingRecipesService} from '../api-landing-recipes.service'
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.page.html',
styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
datauser: any[];
constructor( public api: ApiLandingRecipesService) { }
ngOnInit() {
this.getDataUser();
}
async getDataUser() {
await this.api.getDataUser()
.subscribe(res => {
console.log(res);
this.datauser =res;
console.log(this.datauser);
}, err => {
console.log(err);
});
}
and Here's my service file:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const apiUrl = "https://example.com/showimages";
#Injectable({
providedIn: 'root'
})
export class ApiLandingRecipesService {
constructor(private http: HttpClient) { }
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError('Something bad happened; please try again later.');
}
private extractData(res: Response) {
let body = res;
return body || [] ; }
getDataUser(): Observable<any> {
return this.http.get(apiUrl, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
}
It's because filenames is indeed a string (a json string representation of the array) and not an array.
Try converting the string into an array first.
JSON.parse(filenames)[0]
The value of filenames here is a string and not an array, which is why you're getting [ when you try to access the first element.
You probably need to parse the value, here's an example (assuming datauser) is the JSON data you've shown us.
let filename = JSON.parse(datauser[0].filenames)[0]

Angular6 error: the data which I am getting from api is in the string format,below is the response image

hi want to show the data from my api to my frontend (Angular 6), but this error comes up: I am using HttpClient method from angular 6 I am new to angular
Angular6 error: the data which I am getting from api is in the string format, I need to convert it to object, below is the response image
this is model.ts
export class Incident {
public Title: string;
public status: string;
constructor(Title: string, status: string) {
this.status = status;
this.Title= Title;
}
}
this is component
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Incident } from '../../shared/incidents.model';
import { DataStorageService } from '../../shared/data-storage.service';
#Component({
selector: 'app-active-incident',
templateUrl: './active-incident.component.html',
styleUrls: ['./active-incident.component.css']
})
export class ActiveIncidentComponent implements OnInit {
incidents: Incident[];
constructor(private router: Router, private dataStorageService: DataStorageService) { }
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Incident[]) => this.incidents = data,
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}
this is service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Incident } from './incidents.model';
#Injectable()
export class DataStorageService {
constructor(private http: HttpClient) {}
getIncidents(): Observable<Incident[]> {
console.log('Getting all incidents from server');
return this.http.get<Incident[]>
('api/url');
}
}
my json
{
"Events": ["{'title': 'some title', 'Incident_Status': 'status'}",
"{'title': 'some title', 'Incident_Status': 'status'}"]
}
html view
<div class="card" *ngFor="let incident of incidents">
<div class="card-header">
<span class="badge badge-danger"></span>{{incident.Title}}
<span class="badge badge-danger"></span>{{incident.Incident_Status}}
</div>
</div>
You are trying to iterate an object instead of an array. This happens because the list of events are inside the Events key, but you aren't accessing it to extract the list of events. Instead you are using the root of the response object.
Corrected code:
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Incident[]) => this.incidents = data.Events, // <--
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}

I get a error while publishing a app. The error is property json does not exist on type object

when I try to test the app in Ionic serve command, I didn't get any error. But when i try to publish the app, I get the error as "property json does not exist on type object" . The error takes place during the transpile stage:
How to solve this problem? I tried with every possibility, but i didn't get my problem solved.
Home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { WeatherProvider } from '../../providers/weather/weather';
import { Storage } from '#ionic/storage';
//import { Response } from '#angular/http';
//import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weather:any;
location:{
city:string,
state:string
}
constructor(
public navCtrl: NavController,
private weatherProvider:WeatherProvider,
private storage: Storage) {
}
ionViewWillEnter(){
this.storage.get('location').then((val)=>{
if(val!=null){
this.location = JSON.parse(val);
}else{
this.location = {
city: 'Chennai',
state: 'TN'
}
}
this.weatherProvider.getWeather(this.location.city,this.location.state)
// .map((res: Response) => res.json() )
.subscribe(weather => {
this.weather = weather.current_observation;
});
});
}
}
Weather.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
//import { Response } from '#angular/http';
//import 'rxjs/add/operator/map';
//import 'rxjs/Rx';
#Injectable()
export class WeatherProvider {
apiKey = '6d3243fb22b01d0c';
url;
constructor(public http: HttpClient) {
console.log('Hello WeatherProvider Provider');
this.url = 'http://api.wunderground.com/api/'+this.apiKey+'/conditions/q';
}
getWeather(city, state){
return this.http.get(this.url+'/'+state+'/'+city+'.json')
// .map(res => res.json());
// .map((res: Response) => res.json() );
}
}
Typescript is all about typing. So you should state the type of object you'are receiving from the method getWeather. Start by creating a class Weather at the end of home.ts (look below)
class Weather {
current_observation: string;
}
and make this change:
this.weatherProvider.getWeather(this.location.city,this.location.state)
// .map((res: Response) => res.json() )
.subscribe((weather: Weather) => {
this.weather = weather.current_observation;
});
});
}
ionViewWillEnter(){
this.storage.get('location').then((val) => {
if(val != null){
this.location = JSON.parse(val);
} else{
this.location ={
city: 'miami',
state: 'FL'
}
}
//Try below code
this.weatherprovider.getweather(this.location.city, this.location.state).subscribe(result => {
let weather:any = result;
this.weather = weather.current_observation;
console.log(this.weather);
});
});
}

Get JSON data from API with Angular 2

I am trying to get some JSON data by API that I have created, but it does not receive it. I have used the following Angular code:
getBook(id: string){
return this._http.get(this.url + 'books/' + id)
.map(res => {
console.log(res.json()); //It does not show anything
return res.json();
})
However the getBooks() method has no problems getting the data. There are no errors in the browser console.
This is the whole service code:
import { Injectable } from '#angular/core';
import { Http } from "#angular/http";
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
#Injectable()
export class LibrosService {
url: string = "http://localhost/API/public/index.php/api/";
constructor(private _http: Http) { }
getBooks(){
return this._http.get(this.url + 'books')
.map(res => res.json()); //it works
}
getBook(id: string){
return this._http.get(this.url + 'books/' + id)
.map(res => {
console.log(res.json()); //it does not work
return res.json();
})
}
Sorry for my English if it is not very good and thank you for your help.
In Service
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
In Component
getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
Fortunately, a friend helped me find the solution because the most frustrating thing was console did not show any errors. And the problem was not in service, it was in component.
Here is my solution:
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { BooksService } from "app/services/books.service";
import { Subscription } from "rxjs/Subscription";
#Component({
selector: 'app-book',
templateUrl: './book.component.html'
})
export class BookComponent implements OnInit {
public book: any =[];
private sub: Subscription;
public errorMessage: string;
constructor( private _activatedRoute: ActivatedRoute,
private _booksService: BooksService ) {}
ngOnInit() {
this.sub = this._activatedRoute.params
.subscribe(params => {
let id = +params['id'];
this.getBok(id);
});
}
getBok(id){
this._booksService.getBook(id)
.subscribe(book => {
this.book = book,
error => this.errorMessage = <any>error
});
}
}
Thanks all of you for your help.

Accessing Data from Database for display

UPDATE: I figure it would be easier if I just made a Gist to share with the code that's being utilized in this.
CODE: https://gist.github.com/strawmr/15a22bf5118642ff130f215511982b80
ORIGINAL: I'm working on a new system at work that will allow data to be read and updated directly to a database. Part of this involves Angular 2 and Typescript.
During the development I've run into an issue with it not loading the information. It shows me solely the "loading incidents" that is used as a placeholder inside the element tags.
What could I be missing that is causing the data to not appear or the code itself to not function properly? Below are the code snippets.
incident.service.ts
import { Injectable } from "#angular/core";
import { Http, Response } from "#angular/http";
import { SpringfieldService } from "./springfield.service";
import "rxjs/add/operator/map";
import { Incident } from "./incident";
#Injectable()
export class IncidentService extends SpringfieldService {
private url = this.baseUrl + "Incident";
constructor(private http: Http) {
super();
}
getAll() {
return this.http.get(this.url)
.map((res: Response) => res.json());
}
getIncident(incidentId: number) {
return this.http.get(this.url, incidentId)
.map((res: Response) => res.json());
}
saveIncident(incident: Incident) {
return this.http.put(this.url, incident)
.map((res: Response) => res.json());
}
addIncident(incident: Incident) {
return this.http.post(this.url, incident)
.map((res: Response) => res.json());
}
deleteIncident(incident: Incident) {
return this.http.delete(this.url, incident)
.map((res: Response) => res.json());
}
}
incident.component.ts
import { Component } from "#angular/core";
import { IncidentService } from "./incident.service";
import { Incident } from "./incident";
#Component({
selector: "rpcs-incident",
templateUrl: "/app/incident.component.html",
providers: [IncidentService]
})
export class IncidentComponent {
private incidents: Incident[];
constructor(incidentService: IncidentService) {
incidentService.getAll()
.subscribe(
response => this.incidents = response,
err => console.log("Error: ", err),
() => console.log("Fetch incidents complete.", this.incidents)
);
}
}
incident.component.html
<div class="incidentarticle" *ngFor="let incident of incidents; let i = index; trackBy: incidentId">
<h2>
{{incident.IncidentId}}
<span class="glyphicon glyphicon-edit" (click)="onEdit()"></span>
</h2>
<h3 *ngIf="incident.DateReported != null">Start: {{incident.DateReported | date:'medium'}}</h3>
<!--<div> <span>Applies To:</span> {{newsitem.AppliesTo}}</div>-->
<div>
<span>Description:</span> {{incident.IncidentDescription}}
</div>
<!--<div>
<span>Action Required:</span> {{newsitem.ActionRequired}}
</div>
<div><span>For Further Information:</span> {{newsitem.AdditionalInfo}}</div>-->