3

I want to call a http.get method off my ThemeService and make it as "synchronous" as possible so that it continuous after it gets Theme from the call. I searched on how to do this and stumbled across async and await. I tried to implement this but it didn't quite work. I put some console.log() in the code so i can see what is and what isn't executed. The "IN ASYNC FUNCTION" and "AFTER ASYNC" are executed but not the ones after/in my call on ThemeService.

Because i am new to the async/await functions in typescript i don't know if what I have written is badly or if what i'm trying to do is possible or not.

ngOnInit():void{ let id = +this.routeParams.get('themeId'); async function getTheme(){ console.log("IN ASYNC FUNCTION"); var val = await this.themeService.getTheme(id).subscribe((theme:Theme)=> { this.theme = theme; console.log("IN AWAIT FUNCTION") }); console.log("AFTER AWAIT"); return val; } getTheme(); console.log("AFTER ASYNC"); } 

1 Answer 1

4

You can have it like this (note usage of 'take(1).toPromise()'):

ngOnInit():void { let id = +this.routeParams.get('themeId'); async function getTheme() { console.log("IN ASYNC FUNCTION"); var val = await this.themeService.getTheme(id).take(1).toPromise(); console.log("AFTER AWAIT"); return val; } this.theme = await getTheme(); console.log("AFTER ASYNC"); } 

Or a bit shorter:

class MyComponent implements OnInit { async ngOnInit() { let id = +this.routeParams.get('themeId'); this.theme = await this.themeService.getTheme(id).take(1).toPromise(); console.log("AFTER ASYNC"); } } 

Hope this helps.

Sign up to request clarification or add additional context in comments.

7 Comments

I tried it both ways but nothing worked out, this.theme didn't get a value. The "AFTER ASYNC" isn't logged in the console. If i put a console.log("int method") within the getTheme() methode, It doesn't log it in the console either
try first replacing your themeService.getTheme() async method with some dummy method that just logs when its get called and returns something like Promise.resolve(), to see that its not the issue with themeService.
I changed the content of getTheme to just log something in console and return Promise.resolve() instead of Observable<Theme> and that works. But the getTheme methode works if i use it normally instead of in async/await.
Ok. Can you replace content of getTheme to return with something like: rx.Observable.just(123), and see if it will work.
He still shows the logs after i return an Observable but once i try to get the value of the observable with the ".take(1).toPromise()" it doesn't log the "AFTER SYNC" message
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.