在订阅方法中解析数据之前,如何使函数(调用订阅方法)从返回值开始等待?

时间:2019-04-17 14:19:06

标签: angular async-await subscribe

我对Angular还是陌生的,在这里感谢一些指导。我的AuthService中的 userLoggedIn 函数始终返回 false ,因为该函数返回变量 userIsLoggedIn 的值,该变量最初被分配为 false >并且在执行return语句之前,它永远不会到达传递给订阅方法的回调函数中的代码块-this.userIsLoggedIn=res.tokenValid;。我认为这是由于javascript处理函数的异步性质引起的,但是如何在完全执行回调函数之前阻止执行到达 return语句,以便我的函数可以返回 true 如果我的响应对象的 validToken 属性包含 true 值?

我尝试了以下操作,但没有帮助:

  1. 在我的回调函数上使用了异步等待-         this.httpReq.verifyToken(token) .subscribe(**async** res =>{ this.userIsLoggedIn= **await** res.tokenValid; })

  2. 使整个userLoggedIn函数 async-await

    **async** userLoggedIn():boolean{
         **await** this.httpReq.verifyToken(token)
     }
    
//Auth Service
export class AuthService {
    userIsLoggedIn=false;
    constructor(private router:Router, private repo:ProductRepository, 
        private httpReq:HttpRequestService) {}

    userLoggedIn():boolean{
        const token=this.getLocalToken();

        if(!token){
            return false;
        }

        this.httpReq.verifyToken(token)
            .subscribe(async res =>{
            this.userIsLoggedIn=await res.tokenValid;
            })

        return this.userIsLoggedIn;

    }
}


//verifyToken method in my HttpRequestService
export class HttpRequestService {

    constructor(private http: HttpClient) { }

    verifyToken(token:string){
        const headers=new HttpHeaders({
          'Content-Type':'application/json',
          'Authorization':token
        })

        return this.http.post<{message:string, tokenValid:boolean}>('http://localhost:3000/users/authenticate', null, {headers:headers})

    }
}

2 个答案:

答案 0 :(得分:1)

由于您的sed -E 'h;s/.*\[([^]]*)\].*/\1/;s/"//g; G;s/(.*)\n(.*)\[[^]]*\](.*)/\2"\1"\3/' d 函数正在执行HTTP调用,因此该函数应该异步发生(一段时间后完成)。

提示::要更好地了解userLoggedIn(),请查看回调,异步/等待,promise,可观察对象。

答案:

sync vs async

小词汇表:

of :创建一个新的可观察到的提供的参数
点击:不影响流,可以执行响应而没有副作用的操作
switchMap :类似于 userLoggedIn(): Observable<boolean>{ // Make sure this is sync or need to be chained with the observable below const token = this.getLocalToken(); if(!token){ return of(false); } else { return this.httpReq.verifyToken(token).pipe( // Use the tap operator to update some inner class variable tap((res) => this.userIsLoggedIn = res.tokenValid) // We do have the response, if there is ok you can return true. You can add additional validations. switchMap((res) => res ? of(true) : of(false)), // Catch errors, do something with them catchError((err) => of(false)) ) } }

...,最后调用如下函数:

.then(() => new Promise()

答案 1 :(得分:0)

您不需要使用异步或等待。 HttpRequestService.verifyToken返回类型为{message:string,tokenValid:boolean}的Observable。您可以让userLoggedIn函数也返回此Observable,然后订阅userLoggedIn。您需要熟悉RX Observables,但是您可以让HttpRequestService.verifyToken返回Promise。在这种情况下,这不是一个坏主意。