[英]Angular 6: How do return data from observable?
我正在嘗試使用isAuth
函數從后端檢索數據並使該函數返回該數據。 然后,當我調用該函數時,數據將返回到變量中,並且可以使用該數據。
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService implements CanActivate {
constructor( private http: HttpClient, private router: Router ) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
var isAuth = this.isAuth()
console.log(isAuth);
}
isAuth(){
let obs = this.http.get('server/page/auth');
obs.subscribe((res) => { return res});
}
}
當我控制台日志isAuth時,我得到undefined
。 據我了解,這是因為它不是異步的。 在node.js中,您基本上會在該函數的前面await
,這可以解決問題。 我該怎么辦? 如何將數據從isAuth
返回到變量中?
您需要從isAuth
返回observable,並從canActivate
函數進行訂閱
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.isAuth().subscribe((res) => { console.log(res);});
}
isAuth(){
return this.http.get('server/page/auth');
}
您的isAuth
函數沒有返回值。 您訂閱了HTTP請求,但實際上不對其執行任何操作。
obs.subscribe((res) => { return res });
return res
從內部匿名函數返回。 它不會從isAuth
返回!
角度文檔:
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}
因此,有很多方法可以做到這一點。 無論如何, canActivate
函數將必須返回一個Observable,該Observable發出一個布爾值,一個解析為布爾值的Promise或布爾值原語。 您無法返回訂閱。 如果您使用的是Observables,則可以嘗試以下操作:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.isAuth();
}
isAuth(): Observable<boolean> {
return this.http.get('server/page/auth').map(res => res.message === 'success');
// You are returning the Observable here
// Do use 'map' and other rxjs stream operators, do not use subscribe!!!
// Using subscribe will change your return value to 'Subscription', not 'Observable'!!
}
您可以查看有關Observables,觀察者,訂閱和訂閱者的RxJS文檔。 祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.