Reputation: 1734
I'd like to get the following response into a string rather than an observable.
getFacebookPhoto(uid: string): Observable<any> {
let results = this.http.get('https://graph.facebook.com/' + uid + '/picture?height=200&redirect=false')
.map(response => response.json().data.url.)
return results
}
I need to populate a list of available photos for my users to choose from. I'm binding the url's of those photos to the template with interpolation with something like {{ selectedPic }}
. Ideally, something like, (click)="selectedPic = gravatarUrl"
would change the value of selectedPic
to the value of gravatarUrl
, or any of the variables in my component that have string values of a url.
The issue is that facebookPhoto
is an observable. I'd like to store the emission as a string.
This achieved the goal of storing the emission in the string type variable selectedPic
:
this.memberCreationService.getFacebookPicUrl(uid)
.subscribe(picUrl => this.selectedPic = picUrl)
Is there a way to do this without creating a subscription, however? Something that gets the emission and disposes of the observable maybe...
Upvotes: 1
Views: 8643
Reputation: 4214
In angular2's Http from '@angular/http'. http.get will always return an Observable object, you can see it in the function's signature:
get(url: string, options?: RequestOptionsArgs): Observable<Response>;
This is because this function runs asynchronously, if when you want to fetch data from a server it will have to wait, so it can't just return the string/json object you requested right away.
You should subscribe to the observable after the function call by using the .subscribe
function it returns, or use .toPromise()
if you imported the 'rxjs/operator/add/toPromise'
module
ex:
getFacebookPhoto("abcd123").subscribe(response => {
this.myObject = response.json();
}
I'd suggest you read about Observables or Promises here.
Also, you don't need to use {{}} in here: (click)="{{selectedPic = gravatarUrl}}"
Upvotes: 1
Reputation: 3612
No, you're subscribing to the event, and the data literally isn't present until it reaches the application.
The Http module is making an async web request to fetch data, so you need to subscribe to be informed when the data is present (and take some action, such as assign the data to a variable.
The subscription is necessary.
Upvotes: 1