从休息电话返回数据

时间:2017-05-29 13:36:40

标签: angular angular2-components

在组件中我有以下内容:

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返回数据。

1 个答案:

答案 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>

异步管道将自动为您管理订阅。