【问题标题】:Angular 2. Service return undefinedAngular 2. 服务返回未定义
【发布时间】:2016-12-03 10:42:08
【问题描述】:

我有 2 个服务(AuthService 和 AuthRedirectService)

AuthService 使用 Http 服务从服务器获取简单数据{"status": 4} 和return response.json().status

AuthRediredService 实现 OnActivate 并使用 AuthService 服务。这是唯一的方法 AuthService.GetStatus() : number,但它返回undefined

AuthService

GetStatus(): number {
    let status: number;
    this.http.get(this.host + "/api/auth/")
    .subscribe((value: Response) => {
      status = value.json().status;
      console.log(value.json().status); // write real number 4
    });
    return status; // 4
  }

AuthRedirectService

  canActivate() : boolean
  {
    console.log(this.auth.GetStatus()); // undefined  !!!!!!!!
    if(this.auth.GetStatus() == StatusCode.Logined)
    {
      // redirect code
      return false;
    }
    return true;
  }

【问题讨论】:

  • http.get 是异步的,在它解析之前您已经从GetStatus() 返回。
  • 您可以在此处查看 Gunter 的回答:stackoverflow.com/questions/38425461/… 以获得灵感并更深入地了解异步 canActivate() 实现。

标签: angular typescript dependency-injection angular-services


【解决方案1】:

这是一个简单的 Javascript 异步问题,与 Angular2 无关。

在 javascript 中,当您调用异步方法时,例如可能在 10 分钟后解决的 http 调用,您不能期望立即得到结果:

比方说:

   myAsyncFunction(){
       let theResult;  // First: this line fired
       callAHttpServiceThatTakes1Minute() // Second: we called the function that returns the result in 1 mutine
       .then((res)=>{
          theResult = res; // Forth :  will be available after 1 minute 
       });

       console.log(theResult); // Third : This is undefined because number Forth hasn't finished yet.
   }

要解决你的问题,你的路线应该是这样的:

 { path : 'home' , component : HomePageComponent , resolve : { user : GetStatusResolver } } ,

然后:

@Injectable()
export class GetStatusResolver implements Resolve {
    constructor ( private auth : AuthService ) {
    }

    resolve ( route : ActivatedRouteSnapshot , state : RouterStateSnapshot ) : Observable<User> {
        return  this.auth.GetStatus() ;
    }
}

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2019-07-28
    • 1970-01-01
    • 2017-11-23
    • 2018-04-02
    相关资源
    最近更新 更多