In Angular 2+, with async pipe, I'm wondering why the call of a function returning a promise only do an infinite loop and crash eventually.
- Why cannot we call a function returning a promise directly from the template of a component in the case of an async task?
Without that, we absolutely have to have properties declared within the component for each time we want to do an async job.
In the following example, it's the case of the property "Articles" which will be used to retrieve the data of the Promise, and it will work.
However doing a "shortcut" by using the function returning a promise will simply fail and eat all memory (tested on chrome, and on nodejs).
- Why this behaviour is occuring?
This is a full example (be careful, it will crash your browser if you try it):
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<p>CASE THAT WORKS PERFECTLY</p>
Getting value from an indirect call:
{{Articles|async}}
</div>
<div>
<p>CASE THAT WILL CRASH YOUR BROWSER (memory eater)</p>
Getting value from a direct call to the function returning the Promise-string :
{{simulateDb()|async}}
</div>
`,
})
export class App {
Articles:string;
constructor() {
this.Articles = ( this.simulateDb());
}
simulateDb()
{
return new Promise((a,b)=>{
a('this is a result');
});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [
],
bootstrap: [ App ]
})
export class AppModule {}