How to pass id to the routing table?
http://localhost:4200/user/products/undefined
src/app/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/app/products.service.ts:
How to pass a userid
to the getProducts(userid)
method. Even after refreshing the page?
@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');
}
}
in the link was also userid
src/app/navbar/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>