0

In a component I have the following:

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};
}

I want to return the data from the restCall inside getLocalEvent to the this.localEventEdit variable in ngOnInit.

This is the 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)
    );
}

Any ideas? At this point I can only return return {name: "asdasd", languageId: 1, locationId: 1}; but I want to return the data from the restcall.

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

0

You can not return an asynchronous value in a synchronous way. The recommended way is to use observables and the async-pipe like the following:

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>

The async pipe will automatically manage the subscription for you.

Markus Kollers
  • 3,508
  • 1
  • 13
  • 17