![](/img/trans.png)
[英]Angular not updating view when changed by service called from controller
[英]angular2 view not updating data changed from shared service
我試圖顯示來自共享服務的數據,但未顯示。 任何人都可以請幫我,我從幾天開始就努力做到這一點。 我已經嘗試了NgZone和ChangeDetectorRef,但對我不起作用。
home.component.html
<div *ngFor="let order of orders " class="order-cards">
<div class="order-card">
<div class="btn-order-card">
<button type="submit" class="btn btn-success " (click)="viewOrder(order)">View the Order </button>
</div>
</div>
</div>
home.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SharedService } from '../services/shared.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { constructor( private route: Router, private sharedService: SharedService) { } ngOnInit() { } viewOrder(order) { this.route.navigate(['../view-order']) this.sharedService.viewOrderValues(order); } }
shared.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; Injectable() export class SharedService { constructor() { } private viewOrderSource = new Subject<any>(); viewOrder$ = this.viewOrderSource.asObservable(); viewOrderValues(data: any) { this.viewOrderSource.next(data); return data; } }
視圖order.component.ts
import { Component, OnInit } from '@angular/core'; import { SharedService } from '../services/shared.service'; @Component({ selector: 'app-view-order', template: '{{orderValues}}', styleUrls: ['./view-order.component.scss'] }) export class ViewOrderComponent implements OnInit { orderValues: any; constructor(private sharedService: SharedService) { } ngOnInit() { this.sharedService.viewOrder$.subscribe((data) => { this.orderValues = data; }); } }
我認為您的方法是錯誤的。
您應該使用基於路由的Resolve
並將參數作為id傳遞給組件,以便在加載組件時可以獲取數據。
修改了shared.service.ts
以支持基於ID的搜索:
@Injectable()
export class SharedService {
private orders = []; // initialize or fetch from service, IDK
ordersChanged = new Subject<any[]>();
constructor() { }
addOrder(order: any) {
this.orders.push(order);
this.ordersChanged.next(this.getOrders());
}
getOrders(): any[] {
return this.orders.slice();
}
getOrder(id: number) {
// your logic to find order
return this.orders[id];
}
}
在您的home.component.html
:
<div *ngFor="let order of orders; let i = index" class="order-cards">
<div class="order-card">
<div class="btn-order-card">
<button
type="submit"
class="btn btn-success"
(click)="viewOrder(i)">View the Order</button>
</div>
</div>
</div>
和相應的home.component.ts
中的home.component.ts
:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
orders: string[];
subscription: Subscription;
constructor(private route: Router, private sharedService: SharedService) { }
ngOnInit() {
this.orders = this.sharedService.getOrders();
this.subscription = this.sharedService.ordersChanged.subscribe(orders => this.orders = orders);
}
viewOrder(index: number) {
this.route.navigate(['/view-order', index])
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
您可以創建一個OrderResolver
服務:
@Injectable()
export class OrderResolver implements Resolve<any>{
constructor(private sharedService: SharedService) { }
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): string | Observable<string> | Promise<string> {
const id = +route.params['id'];
return this.sharedService.getOrder(id);
}
}
您可以在上面輕松插入Router
,並在沒有給定ID的訂單的情況下進行處理。
在路由模塊類中,更改view-order
路徑以接受參數作為id並使用解析器在路由加載期間查找順序:
{
path: 'view-order/:id',
component: ViewOrderComponent,
resolve: { order: OrderResolver }
}
然后在您的ViewOrderComponent
:
export class ViewOrderComponent implements OnInit {
orderValues: any;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.orderValues = this.route.snapshot.data['order'];
}
}
更改
private viewOrderSource = new Subject<any>();
至
private viewOrderSource = new BehaviorSubject<Object>(null);
在shared-seriice.ts中
您必須將列表設置為數據副本。 除非將數據重置為完全不同的對象或數組,否則角度不會意識到其已更改。
您可以將this.arrayName = this.arrayName.slice()用於數組; 或對於對象var objName = Object.assign({},objName)
試着做
this.sharedService.viewOrderValues(order);
this.route.navigate(['../view-order'])
我覺得您正在瀏覽,所以它沒有調用該函數,因此沒有調用您的觀察者。
home.component.html引用變量“ orders”。 此變量在home.component.ts中不存在。 當您的服務返回數據時,您可以將其另存為實例變量,並在html中進行引用。
編輯:我相信您也可以直接從您的服務綁定到可觀察對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.