组件var未定义

时间:2017-06-14 15:26:00

标签: angular typescript

我调用服务后,我的var User未定义。这是代码:

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
  }

这是我的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);
    }
}

console.log()显示未定义。

谢谢!

2 个答案:

答案 0 :(得分:0)

您需要在订阅中放置console.log,

  this.appService.getUser().then(user => { this.user = user; 
      this.setUserRoles();}
      console.log(this.user)      
  )
  getUser(): User{
     if(this.user){
      return this.user
      };
  }

答案 1 :(得分:0)

getUser()是异步调用,因此需要一些时间来更新用户值,但是在调用getUser()调用后将返回语句并将返回语句。所以return user将返回null值

你应该把你的控制台声明放在声明中。

getUser(): User{
      this.appService.getUser().then(user => { this.user = user; this.setUserRoles();
console.log(this.user);
})
  }