Изучаю angular 2 и застрял. В гайде написано:
Цитата (https://angular.io/docs/ts/latest/guide/server-communication.html) |
While promises may be more familiar, observables have many advantages. Don't rush to promises until you give observables a chance. |
{
entities: [
{ name: 'parent1', childrenUrl: '/api/parents/parent1/children' },
{ name: 'parent2', childrenUrl: '/api/parents/parent2/children' },
....
]
}
import { ChildModel } from './child.model';
export class ParentModel {
name: string;
children: ChildModel[];
}
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { ChildService } from './child.service';
import { ParentModel } from './parent.model';
@Injectable()
export class ParentService {
private parentsUrl = '/api/parents.json';
constructor(
private http: Http,
private childService: ChildService
) {
}
getParents(): Observable<ParentModel[]> {
return this.http.get(this.parentsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
return response.json().entities;
}
private handleError(error: any) {
// ...
}
}
export class ChildModel {
name: string;
}
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { ChildModel } from './child.model';
@Injectable()
export class ChildService {
constructor(private http: Http) {
}
getChildren(childrenUrl): Observable<ChildModel[]> {
return this.http.get(childrenUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
return response.json().entities;
}
private handleError(error: any) {
// ...
}
}