如何根据 Angular 中的变化更新 html 中的订阅值?
How to update subscribed value in html on change in Angular?
点击“编辑”后,“editStatus”函数被调用,此时“order.status”的值正在变化。但 html 视图保持不变 - 显示订单的旧状态。它仅在刷新页面后发生变化。如何让状态在更改后显示更新的变量?
html:
<div *ngIf="order">
<p>Id:<b> {{ order._id }}</b></p>
<p>Status:<b> {{ order.status }}</b></p>
</div>
<button (click)="editStatus(order)">Edit</button>
ts 文件:
private subscribe: Subscription;
order: Order;
constructor(private orderService: OrderService, private route: ActivatedRoute, public router: Router) { }
ngOnInit() {
this.subscribe = this.route.params.pipe(
map(({ id }) => id),
switchMap((id: string) => this.orderService.getOrderById(id)))
.subscribe((res) => {
this.order = res;
});
}
ngOnDestroy() {
this.subscribe.unsubscribe();
}
editStatus(order) {
const orderEdited = { order, status: 'order_canceled' };
this.orderService.editStatus(orderEdited).subscribe(
res => {
console.log(res);
},
err => console.log(err)
);
}
订购服务:
private userOrdersUrl = 'http://localhost:3000/api/auth/user-orders';
getOrderById(orderId): Observable<Order> {
return this.http.get<Order>(`${this.userOrdersUrl}/${orderId}`);
}
editStatus(order) {
return this.http.put<Order>(this.userOrdersUrl, order);
}
看起来像学生作业...
您没有将更新后的订单分配给您的变量。更改为以下内容:
res => {
this.order = res;
},
点击“编辑”后,“editStatus”函数被调用,此时“order.status”的值正在变化。但 html 视图保持不变 - 显示订单的旧状态。它仅在刷新页面后发生变化。如何让状态在更改后显示更新的变量?
html:
<div *ngIf="order">
<p>Id:<b> {{ order._id }}</b></p>
<p>Status:<b> {{ order.status }}</b></p>
</div>
<button (click)="editStatus(order)">Edit</button>
ts 文件:
private subscribe: Subscription;
order: Order;
constructor(private orderService: OrderService, private route: ActivatedRoute, public router: Router) { }
ngOnInit() {
this.subscribe = this.route.params.pipe(
map(({ id }) => id),
switchMap((id: string) => this.orderService.getOrderById(id)))
.subscribe((res) => {
this.order = res;
});
}
ngOnDestroy() {
this.subscribe.unsubscribe();
}
editStatus(order) {
const orderEdited = { order, status: 'order_canceled' };
this.orderService.editStatus(orderEdited).subscribe(
res => {
console.log(res);
},
err => console.log(err)
);
}
订购服务:
private userOrdersUrl = 'http://localhost:3000/api/auth/user-orders';
getOrderById(orderId): Observable<Order> {
return this.http.get<Order>(`${this.userOrdersUrl}/${orderId}`);
}
editStatus(order) {
return this.http.put<Order>(this.userOrdersUrl, order);
}
看起来像学生作业...
您没有将更新后的订单分配给您的变量。更改为以下内容:
res => {
this.order = res;
},