在组件中我有以下内容:
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};
}
我想将getLocalEvent
内的restCall数据返回到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返回数据。
答案 0 :(得分:0)
您无法以同步方式返回异步值。建议的方法是使用observables和async-pipe,如下所示:
<强> component.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);
}
<强> service.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));
}
<强> component.html 强>
<div>{{ localEventEdit$ | async | json }}</div>
异步管道将自动为您管理订阅。