【发布时间】:2022-02-02 20:29:22
【问题描述】:
我正在使用带有路由的 Angular 材质。在单击事件之后,我希望我的应用程序转到包含参数 currentUser 的 URL。以下是app.component.html文件中的点击事件:
<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 {}
问题是当我执行app和click事件时,显示如下错误:
Http 失败响应 http://localhost:8080/carts/cart_by_user/$%7Buser%7D: 400 OK
控制台出错:
ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。 URL 段:'carts/cart_by_user;id=9;code=000;...'
app.component.ts 文件:
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}');
}
}
【问题讨论】:
标签: html angular typescript routes angular-material