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?
Subscribe() is a method in Angular that connects the observer to observable events. Whenever any change is made in these observable, a code is executed and observes the results or changes using the subscribe method. Subscribe() is a method from the rxjs library, used internally by Angular.
Observable values can be retrieved from any locations. The source sequence is first pushed onto a special observer that is able to emit elsewhere. This is achieved with the Subject class from the Reactive Extensions (RxJS). Store value onto the observer.
The async pipe in angular will subscribe to an Observable or Promise and return the latest value it has emitted. Whenever a new value is emitted from an Observable or Promise, the async pipe marks the component to be checked for changes.
You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.
You also can't have such code in the class directly. It needs to be moved into a method or the constructor.
What you can do is not to subscribe()
directly but use an operator like map()
export class DataComponent{ someMethod() { return this.http.get(path).map(res => { return res.json(); }); } }
In addition, you can combine multiple .map
with the same Observables as sometimes this improves code clarity and keeps things separate. Example:
validateResponse = (response) => validate(response); parseJson = (json) => JSON.parse(json); fetchUnits() { return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson); }
This way an observable will be return the caller can subscribe to
export class DataComponent{ someMethod() { return this.http.get(path).map(res => { return res.json(); }); } otherMethod() { this.someMethod().subscribe(data => this.data = data); } }
The caller can also be in another class. Here it's just for brevity.
data => this.data = data
and
res => return res.json()
are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...)
or map(...)
to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod()
is completed, the data wasn't received yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With