如果用户有商店,Angular 2重定向

时间:2017-04-22 10:20:44

标签: ruby-on-rails api angular

如果用户-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令牌。感谢帮助。对不起我的英文

3 个答案:

答案 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']);
                     }
                }
        });