如果用户-id(this.authTokenService.currentUserData.id)有商店(owner_id),我如何进行重定向。 Shop.component.ts
owner_id :number;
private sub: any;
ngOnInit() {
this.sub = this.httpService.getShops().subscribe(params => {
this.owner_id = this.authTokenService.currentUserData.id ;
console.log(this.sub)
console.log(this.owner_id)
});
if (this.sub) {
this.router.navigate(['/profile']);
}
Http.service.ts
getShops(){
return this.http.get('http://localhost:3000/shops.json')
}
我将Rails 5用于api和auth令牌。感谢帮助。对不起我的英文
答案 0 :(得分:1)
private sub: any;
ngOnInit() {
this.httpService.getShops()
.subscribe(params => {
// code here is executed when the response arrives from the server
this.owner_id = this.authTokenService.currentUserData.id ;
console.log(this.sub)
console.log(this.owner_id)
if (this.sub) {
this.router.navigate(['/profile']);
}
});
// code here is executed immediately after the request is sent
// to the server, but before the response arrives.
}
如果代码取决于您从sub
获得的subscribe
,那么您需要在subscribe
回调中移动代码,否则它将在this.sub
之前执行获得一个价值。
答案 1 :(得分:1)
我无法在这里完成你的意图,但这段代码似乎就是你所追求的。希望这有帮助
ngOnInit() {
this.getUserShops(this.authTokenService.currentUserData.id)
.subscribe((ownerShops) => {
if (ownerShops.length > 0) {
// User has at least 1 shop
this.router.navigate(['/profile']);
} else {
// User has no shops
}
})
}
getUserShops(ownerId: number): Observable<any> {
return this.httpService
.getShops()
// Map the returned array to a filtered subset including only the owners id
.map((shops: any[]) => shops.filter(shop => shop.owner_id === ownerId));
}
// http.service.ts
export class HttpService {
getShops(): Observable<Shop[]> {
return this.http.get('http://localhost:3000/shops.json')
.map((res: Response) => res.json())
}
}
export interface Shop {
owner_id: number | null;
}
编辑:添加更新以显示示例http.service.ts typings
答案 2 :(得分:0)
试试这段代码。
owner_id :number;
private sub: any;
ngOnInit() {
this.httpService.getShops().subscribe(
response => {
this.sub = response
if (this.sub.length>0) {
this.router.navigate(['/profile']);
}
}
});