Search code examples
angularrxjsangular2-observables

Angular 2: http.get Response to String


Core Question:

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
}

Additional Information:

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.

Update:

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...


Solution

  • 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}}"