Angular应用添加未接来电后视图不更新问题求助
问题解决:添加未接来电后视图不更新
问题原因
你的组件在ngOnInit时获取了CallService中calls数组的引用,但服务的addCall方法通过this.calls = [...this.calls, call];创建了一个新数组,此时组件内的calls变量仍然指向原来的旧数组引用。Angular的变更检测只会跟踪组件自身变量的引用变化,因此不会察觉到服务中数组的替换,导致视图无法更新新的通话记录。
解决方案
方案1:直接绑定服务的数组(简单快速)
修改组件代码,移除自身的calls数组,直接在模板中引用服务的calls:
组件代码:
import {Component, OnInit} from '@angular/core'; import { Call, CallService } from '../call.service'; @Component({ selector: 'app-missed-calls', styleUrls: ['./missed-calls.component.css'], templateUrl: './missed-calls.component.html', }) export class MissedCallsComponent implements OnInit { constructor(public _callService: CallService) { } // 改为public,让模板可访问 ngOnInit() {} // 无需再赋值calls }
模板代码:
<mat-list> <div mat-header style="color:#043755; font-weight: 700; font-size: 1.8rem; text-align: center;">Anrufe:</div> <mat-list-item *ngFor="let call of _callService.calls;"> <mat-icon mat-list-icon>phone</mat-icon> <div mat-line style="font-size: 1.2rem;">{{call.number}}</div> <div mat-line style="font-size: 1.2rem;"> {{call.date | date}} </div> <div mat-line style="font-size: 1.2rem; color:chocolate;">{{call.status}}</div> </mat-list-item> </mat-list>
方案2:使用Observable实现响应式更新(推荐,符合Angular最佳实践)
通过BehaviorSubject让服务发布数组变化,组件订阅该变化来更新视图:
服务代码:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; export interface Call { number: string; date: Date; status: string; } @Injectable({ providedIn: 'root' }) export class CallService { // 用BehaviorSubject存储数组,初始值为默认通话记录 private _callsSubject = new BehaviorSubject<Call[]>([ {number: '0677/61792248', date: new Date('1/1/14'), status: 'Verpasst'}, ]); // 暴露可观察对象供组件订阅 public calls$ = this._callsSubject.asObservable(); constructor() { } getCalls() { return this._callsSubject.value; } addCall(call: Call) { // 创建新数组并通知订阅者 const updatedCalls = [...this._callsSubject.value, call]; this._callsSubject.next(updatedCalls); } }
组件代码:
import {Component, OnInit, OnDestroy} from '@angular/core'; import { Call, CallService } from '../call.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-missed-calls', styleUrls: ['./missed-calls.component.css'], templateUrl: './missed-calls.component.html', }) export class MissedCallsComponent implements OnInit, OnDestroy { public calls: Call[] = []; private callSubscription: Subscription; constructor(private _callService: CallService) { } ngOnInit() { // 订阅服务的数组变化,更新组件的calls this.callSubscription = this._callService.calls$.subscribe(updatedCalls => { this.calls = updatedCalls; }); } ngOnDestroy() { // 组件销毁时取消订阅,避免内存泄漏 this.callSubscription.unsubscribe(); } }
模板代码无需修改,保持原来的*ngFor="let call of calls;"即可。
内容的提问来源于stack exchange,提问作者Lukas.lmst
相关产品推荐
相关产品推荐

