我真的很陌生,我不明白某事。
我有一个CalendarService,我有一个方法getYear(id:string)。 在我的年份模型中看起来像这样
export class Year {
id: string;
number: Number;
months: Month[];
weeks: Week[];
}
我需要的是从Months [](name,numberOfDays等)获取数据。
这就是我的服务外观
@Injectable()
export class CalendarService {
endPoint: string;
private _calendarUrl = '/api/mycalendar';
months: Month[];
year: Date;
constructor(private http: HttpClient) {
}
getYear(id: string): Observable<Year> {
return this.http.get(this._calendarUrl + '?id=' + id)._catch(this.handleError);
}
getYears() {
return this.http.get(this._calendarUrl)
.map((res: Response) => res.json())
._catch(this.handleError);
}
getMonths(yearId: string) {
// get year from db
const year = this.getYear(yearId);
// access months
this.months = year.
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.log(errMsg);
return Observable.throw(error);
}
}
答案 0 :(得分:0)
试试这个。
@Injectable()
export class CalendarService {
endPoint: string;
private _calendarUrl = '/api/mycalendar';
months: Month[];
year: Date;
constructor(private http: HttpClient) {
}
getYear(id: string): Observable<Year> {
return this.http.get(this._calendarUrl + '?id=' + id)._catch(this.handleError);
}
getYears() {
return this.http.get(this._calendarUrl)
.map((res: Response) => res.json())
._catch(this.handleError);
}
// in here you need to do the api call and subscribe for the response.
getMonths(yearId: string) {
const year = this.getYear(yearId).subscribe((response) => {
this.months = response.
});
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.log(errMsg);
return Observable.throw(error);
}
}
答案 1 :(得分:0)
getYear
http
调用返回observable
。所以
您需要subscribe
到observable
getMonths(yearId: string) {
const year = this.getYear(yearId).subscribe((response) => {
this.months = response.months // or response.data.months
});
}