The code snippet below is not functioning as expected. I'm attempting to pass a variable obtained from an rxjs observable function to another function, but I'm uncertain of the correct method to do so and haven't been able to find a suitable example.
For instance, in the following code, the getUserName()
successfully retrieves the this.username
from the JSON response. However, I'm struggling to pass this value to the getUserInfo()
function.
Whenever I try, I always receive undefined
.
import {Component, OnInit, Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import {Post} from './Post';
@Injectable()
export class UserService {
username: any;
constructor(private http: Http) {}
getUserName(){
this.http.get("http://localhost:1337/user").map(res => res.json()).subscribe(
data => this.username = data.username,
err => console.log(err))
}
getUserInfo(){
console.log(this.username);
}
}