【发布时间】:2017-04-20 01:23:07
【问题描述】:
我有一个非常简单的服务,它的工作是从 api/authenticate url 获取 200 或 401。
auth.service.ts
@Injectable()
export class AuthService {
constructor(private http: Http) {
}
authenticateUser(): Observable<any> {
return this.http.get(AppSettings.authenitcationEnpoint)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response;
return body || {};
}
private handleError(error: Response) {
let errMsg: string;
if (error instanceof Response) {
errMsg = `${error.status} - ${error.statusText || ''}`;
} else {
errMsg = error.toString();
}
return Observable.throw(errMsg);
}
}
现在我想在我的 html 中使用它,我知道我可以创建一个订阅者并根据响应或错误代码设置一个变量,但我的问题是我将不得不在整个地方复制代码。我要的很简单
<div *ngIf="authService.AuthenticateUser()">my content</div>
如果它的 401 来自 handleError 则隐藏,否则显示 div。
这就像从 Observable 获取布尔值。我也有 AuthGuard。
authguard.ts
@Injectable()
export class AuthGuard implements CanActivate {
private isActive: boolean = true;
constructor(private authService: AuthService, private router: Router) {
}
canActivate(): boolean {
this.authService.authenticateUser()
.subscribe(() => {},
error => {
if (error.indexOf("401") >= 0) {
let link = ['contactus'];
this.router.navigate(link);
this.isActive = false;
}
});
return this.isActive;
}
}
我不能在 ngIf 中使用 authGuard.canActive()。有没有更简单的方法可以在不重复代码的情况下做到这一点。我很确定 AuthGuard 不起作用,因为它每次都必须返回 true,因为订阅需要时间。
app.component.ts
export class AppComponent {
private isAuthenticated: boolean = false;
constructor(private authService: AuthService,private authGuard: AuthGuard) {
this.authService.authenticateUser()
.subscribe(response => {
if (response.status == 200)
this.isAuthenticated = true;
},
error => {
if (error.indexOf("401") >= 0)
this.isAuthenticated = false;
});
}
}
home.component.ts
export class HomeComponent implements OnInit {
constructor(private http: Http, private authService: AuthService, private utilityService: UtilityService, private homeService: HomeService, private factoryService: FactoryService, private supplierService: SupplierService, private businessAreaService: BusinessAreaService, private router: Router) {
this.authService.authenticateUser()
.subscribe(response => {
if (response.status == 200)
this.isAuthenticated = true;
},
error => {
if (error.indexOf("401") >= 0)
this.isAuthenticated = false;
});
this.customData = new CustomData(http);
}
}
您可以看到很多重复的代码。我正在努力避免重复。
当我调用我的 api 时,会出现一个弹出窗口,输入 windows 用户名/密码以进行 windows 身份验证。在我取消该弹出窗口之前,我没有得到 401。所以我想隐藏我的菜单 + 主页组件。
在我的服务中,我得到 response:200 in map 和未经授权:401 在 catch 块
【问题讨论】:
-
这个 ngIf 来自哪里?我假设的一个组件?拥有该组件的
.ts会很好。 -
如果你不
subscribe到可观察对象,你永远不会有任何结果。 -
最后,一旦你有一个组件(从服务中)获取 http 调用的结果,你可以订阅它并保存值以将其显示到你的视图中,或者使用@987654328 @管道。
标签: angular asynchronous typescript observable