I'm wondering how to get data in Angular 2 and put it in javascript. I've looked at the hero's tutorial and here's what I've come up with so far.
I've created a service with http var in constructor
I've created a function in the service to get articles
GetArticles(subverse : string) : Observable<Article[]> { console.log("GetArticles URL: " + this._getArticlesUrl + "/?subverse="+subverse); return this.http.get(this._getArticlesUrl + "/?subverse="+subverse) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); return body.data || { }; } private handleError (error: Response | any) { // In a real world app, we might use a remote logging infrastructure let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); }
However, I don't understand what an observable is and why I have to use it here?
Now, this code actually calls my URL and the URL actually returns the article data as Json
URL response:
[{"id":1,"userID":"00d85571-e2d3-4817-8698-6aa1b184112b","title":"title","link":"http://google.com","text":"text","subverse":"home","votes":0,"isanon":false}]
Here is my Article class:
export class Article {
id : number;
isanon : boolean;
title: string;
link: string;
text: string;
subverse : string;
userID : string;
votes: number;
}
My question is, how do I get this URL response into an Article[] in my javascript? I've tried
articlesO : Observable<Article[]>;
articles : Article[];
this.articlesO = this.service.GetArticles(this.subverseStr);
this.articlesO.forEach(a => this.articles = a);
But my this.articles
stays undefined
in the code. How am I supposed to read the URL json and turn it into my Articles[]
?
Any help appreciated.
Thanks.