How to set a value from observable to a variable in Angular 2
Because your call is an asynchronous (callback will work only when it is finished, you don't know when), you can't return a value from the asynchronous call, so you need only to assign it when the call is finished.
You need to do your logic which is related to the username
you get in the subscribe
method. You need to create a field to keep the value of the username
for the later use in the class.
@Injectable()
export class AnotherService {
username: any[] = [];
myFinalValue: string;
constructor(private getUsernameService: UsernameService) { }
someMethod() {
this.getUsernameService.getUsername()
.subscribe(username => this.myFinalValue = username.data[0].AccountName));
}
}