I am facing an issue with my User
variable being undefined after calling my service. Here is the code snippet :
import { User } from './user/user';
import { AppService } from './app.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
user: User;
constructor(
private appService: AppService,
){}
getUser(): User{
this.appService.getUser().then(user => { this.user = user; this.setUserRoles();})
console.log(this.user)
return this.user
}
This is the implementation of my AppService :
import { User } from './user/user';
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppService{
private Url = 'https://cara4-c.na.premiertech.com:451/api/data/'; // URL to web api
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
getUser(): Promise<User> {
return this.http.get(this.Url + 'adfsIdentity')
.toPromise()
.then(response => response.json() as User)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
The problem is that the console.log() displays undefined.
Any help would be greatly appreciated. Thanks!