我有一个非常简单的服务,它的工作是从API获得200或401 /验证网址。角2 ngIf可观察?
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然后隐藏否则显示的股利。
它就像从可观测得到的布尔值。我也有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,直到我取消弹出。所以我想隐藏我的菜单+家庭组件。
在我的服务,我得到的回应:200 地图 和未经授权的:401 捕捉块
此ngIf从哪里来?我假定的组件?拥有该组件的'.ts'会很好。 – Maxime
如果你不'订阅'observable,你永远不会有任何结果。 – Maxime
最后,一旦你有一个组件取得一个http调用的结果(来自一个服务),你可以订阅它并保存该值以显示它到你的视图中,或者使用'async'管道。 – Maxime