如何将id传递给路由表

时间:2018-04-01 22:28:31

标签: angular angular-routing

如何将id传递给路由表?

http://localhost:4200/user/products/undefined

的src /应用/ product.module.ts:

const routes = [
  {
    path: `user/products/:userid`,
    canActivate: [AuthGuard],
    component: UserProductsComponent
  },  {
    path: 'users/products',
    component: UsersProductsComponent
  }];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule,
    RouterModule.forChild(routes)
  ],
  declarations: [UserProductsComponent, UsersProductsComponent],
  providers: [
    AuthService,
   // AuthGuard
  ],
  exports: [ UserProductsComponent, UsersProductsComponent, FormsModule ]
})
export class ProductModule { }

的src /应用/ products.service.ts:

如何将userid传递给getProducts(userid)方法。即使刷新了页面之后呢?

@Injectable()
export class ProductsService {

  public jwtToken: string;

  constructor(private http: Http) {
    const theUser: any = JSON.parse(localStorage.getItem('currentUser'));
    if (theUser) {
      this.jwtToken = theUser.token;
    }
  } 

  getProducts(userid) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', `${this.jwtToken}`);
    let options = new RequestOptions({ headers: headers });

    return this.http.get(`http://localhost:4200/user/products/${userid}`, options)
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}
链接中的

也是userid

的src /应用程序/导航栏/ navbar.component.ts:

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" *ngIf="!!authService.isLoggedIn_()" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown"
      aria-haspopup="true" aria-expanded="false">
      My profil
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" >
      <a class="dropdown-item" [routerLink]="['user/products/',userid]">List products</a>

      <a class="dropdown-item" href="#" (click)="logout()">logout</a>
    </div>
</li>

1 个答案:

答案 0 :(得分:0)

试试这个。

const routes = [
{
  path: `user/products/:id`, //id NOT userid
  canActivate: [AuthGuard],  //comment this until you get a valid route.
  component: UserProductsComponent
},  {
  path: 'users/products',
  component: UsersProductsComponent
}];

希望这会有所帮助。如果您有任何其他问题,请告诉我。我也正在用mongodB建立一个大型购物车,如果你看到我的个人资料,你会发现很多关于购物车的信息。只是为了您的信息,我允许任何人访问我的购物应用程序而无需在我的代码中签名,只有他们可以签出他们是否已登录。祝你有愉快的一天。