Angular如何从http获取请求获取结果

时间:2018-07-06 12:31:41

标签: angular asynchronous httprequest get-request

我想做什么:

  • 将标头中带有令牌的获取请求发送到服务器
  • 根据令牌使服务器发回false或true
  • 然后根据服务器的响应,我让用户访问或不访问页面

我正在努力解决的问题:

我挑战要从服务器取回结果,但是由于异步请求,我找不到如何利用它

这是我的代码:

isTokenValid(token: string) : boolean {

    const httpOptions = {
        headers: new HttpHeaders({
          'Authorization': token
        })
    };


    this.httpClient
    .get<boolean>('http://localhost:8080/getValueWithToken', httpOptions)
    .subscribe(
    (response) => {
        this.responseFromServer = response;
    },
    (error) => {
        console.log('Error:', error);
    }
    );

    /*
    while(this.isResponseReceived == false){
    }*/

    return this.responseFromServer;
}

问题是,返回行是在this.responseFromServer = response;之前执行的;所以我不知道如何返回this.responseFromServer:(

在这里我使用isTokenValid函数:

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |boolean {

  //console.log(this.tokenService.isTokenValid(route.params['token']));


  if(this.tokenService.isTokenValid(route.params['token']) == true) {
    return true;
  } else {
    this.router.navigate(['/errorToken']);
  }}

任何帮助将不胜感激:)

3 个答案:

答案 0 :(得分:0)

isTokenValid(): Promise<boolean> {

    return new Promise<boolean>((resolve, reject) => {

    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': token
        })
    };

    this.httpClient
        .get<boolean>('http://localhost:8080/getValueWithToken', httpOptions)
        .subscribe(
            (response) => {
                resolve(response);
            },
            (error) => {
                console.log('Error:', error);
                reject(error);
            }
        );

    });
}

然后

this.tokenService.isTokenValid(route.params['token']).subscribe(
result : boolean => {
    if (result == true)
        return true;
    else
        this.router.navigate(['/errorToken']);
});

答案 1 :(得分:0)

为什么不仅仅返回HTTP调用?

return this.httpClient
.get<boolean>('http://localhost:8080/getValueWithToken', httpOptions);

然后在组件中或任何地方订阅,并听取值+错误?在服务中只需返回可观察到的即可。但是,如果您不希望这样做,则只需返回服务中的订阅即可:

    this.httpClient
         .get<boolean>('http://localhost:8080/getValueWithToken', 
         httpOptions).subscribe(value=>{
               return value;
        }, error=>{// do something with error });

答案 2 :(得分:0)

这是我找到的解决方案:

在第一个文件中:

isTokenValid(token: string) {

    return new Promise((resolve, reject) => {

    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': token
        })
    };

    this.httpClient
        .get<boolean>('http://localhost:8080/getValueWithToken', httpOptions)
        .subscribe(
            (response) => {
                resolve(response);
            },
            (error) => {
                console.log('Error:', error);
                reject(error);
            }
        );

    });
}

然后在第二个文件中:

async canActivate(route: ActivatedRouteSnapshot)  {


  this.reponse = await this.tokenService.isTokenValid(route.params['token']); 

  if(this.reponse)
    return true;
  else
    this.router.navigate(['/errorToken']);

}

感谢您的帮助!