This is What I Want To Do.
@Component({
selector: "data",
template: "<h1>{{ getData() }}</h1>"
})
export class DataComponent{
this.http.get(path).subscribe({
res => return res;
})
}
If getData
was called inside the DataComponent
, You may suggest assign it to a variable like this.data = res
and use i like {{data}}
.But I needed to use like {{getData}}
for my own purpose.Please suggest me?
This question is related to
javascript
angular
typescript
asynchronous
I have used this way lots time ...
@Component({_x000D_
selector: "data",_x000D_
template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
this.http.get(path).subscribe({_x000D_
DataComponent.setSubscribeData(res);_x000D_
})_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
DataComponent.subscribeData=data;_x000D_
return data;_x000D_
}
_x000D_
use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
Source: Stackoverflow.com