Issue
I'm using Angular material with routing. After a click event I want that my app will go to an URL which contains the parameter currentUser. The following is the click event in the app.component.html file:
<button mat-icon-button class="icon shopping cart-icon" aria-label="Icon-button with shopping cart icon" (click)="getCartByUser()" [routerLink]="['/carts/cart_by_user/', currentUser]" routerLinkActive="active">
<mat-icon>shopping_cart</mat-icon>
</button>
app-routing.module.ts:
const routes: Routes = [
{path: 'carts/cart_by_user/:cartOfUser', component: CartComponent, pathMatch:'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The problem is that when I execute the app and the click event, the following error is displayed:
Http failure response for http://localhost:8080/carts/cart_by_user/$%7Buser%7D: 400 OK
Error in the console:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'carts/cart_by_user;id=9;code=000;...'
app.component.ts file:
export class AppComponent implements OnInit {
public currentUser!: User;
public currentLogIn:boolean=false;
constructor(private shared: SharedService, private cartService:CartService){}
ngOnInit():void {
this.shared.castCart.subscribe(cart=>this.cart=cart);
this.shared.castUser.subscribe(currentUser=>this.currentUser=currentUser);
this.shared.castLoggedIn.subscribe(currentLogIn=>this.currentLogIn=currentLogIn);
}
public getCartByUser():void{
if(this.currentLogIn){
this.cartService.getCartByUser(this.currentUser).subscribe(
(response: Cart) => {
this.cart=response;
this.shared.setCart(this.cart);
console.log(response);
},
(error: HttpErrorResponse)=>{
alert(error.message);
}
)
}
}
shared.service.ts:
export class SharedService {
public defaultCart!: Cart;
private cart= new BehaviorSubject<Cart>(this.defaultCart);
castCart = this.cart.asObservable();
public defaultUser!: User;
private user= new BehaviorSubject<User>(this.defaultUser);
castUser = this.user.asObservable();
private loggedIn= new BehaviorSubject<boolean>(false);
castLoggedIn = this.loggedIn.asObservable();
setCart(data: Cart){
this.cart.next(data); }
setUser(data: User){
this.user.next(data); }
setLoggedIn(data:boolean){
this.loggedIn.next(data); }
}
cart.service.ts:
export class CartService {
constructor(private http: HttpClient) { }
public getCartByUser(user : User): Observable<Cart> {
return this.http.get<Cart>('http://localhost:8080/carts/cart_by_user/${user}');
}
}
Solution
Your currentUser holds more than just string. It's an object, that has id=9;code=000... it can't find url ending with such params. How about just use the id of the user? Refactor places where your using url param user object to just user.id.
Answered By - Joosep.P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.