在一个组件中,我有以下内容:
ngOnInit() {
this.route.params.subscribe(params => {
this.localEventEdit = this.getLocalEvent(+params['id'])
console.log(this.localEventEdit)
});
}
getLocalEvent(localEventId: number) {
this.restCall.get("/localevents/" + localEventId, (data) => {
this.localEventEdit = data;
});
return {name: "asdasd", languageId: 1, locationId: 1};
}
我想将数据从 restCall 返回到 getLocalEvent
中的 this.localEventEdit
变量 ngOnInit
.
这是restCall.get
:
//HTTP GET Request
//Default return type is JSON
public get(path: string, callback: (data) => void, returnType: number = RestCall.RETURN_TYPE_JSON) {
this.auth.retrieveToken(path).subscribe(
tokenResponse => {
this.http.get(this.location + path, this.getRequestOptions(returnType))
.map((res: Response) => {
return this.handleResponse(res, returnType);
}).subscribe(
data => callback(data),
error => this.handleError(error)
)
},
tokenError => this.handleError(tokenError)
);
}
有什么想法吗?此时我只能返回return {name: "asdasd", languageId: 1, locationId: 1};
但我想从 restcall 返回数据。
不能以同步方式返回异步值。推荐的方法是使用可观察量和异步管道,如下所示:
组件.ts
localEventEdit$: Observable<any>;
ngOnInit() {
const id = this.route.snapshot.params['id'];
this.localEventEdit$ = this.getLocalEvent(+id);
}
getLocalEvent(localEventId: number): Observable<any> {
return this.restCall.get("/localevents/" + localEventId);
}
服务.ts
get(path: string): Observable<any> {
const url = this.location + path;
return this.auth.retrieveToken(path) // is it right that you don't use the token???
.switchMap(tokenResponse => this.http.get(url, this.getRequestOptions(returnType))
.map((res: Response) => this.handleResponse(res, returnType));
}
组件.html
<div>{{ localEventEdit$ | async | json }}</div>
异步管道将自动为你管理订阅。