2017-05-29 63 views
0

返回的數據在一個組件,我有以下:從REST調用

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

您不能以同步方式返回異步值。推薦的方法是使用觀測和異步管像下面這樣:

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> 

異步管道將自動爲您管理訂閱。