Angular * ng用于直接从服务访问数组

问题描述 投票:1回答:1

目前,我正在从Angular应用中的多个模板访问动态数组。这是一个示例:

array.service.ts

@Injectable()
export class ArrayManagerService {
    public arrayDynamic = [];
    ...
    // some functions calling the api to update dynamic data
}

array-displayer.component.ts

@component({
    selector: 'app-array-displayer',
    templateUrl: 'array-displayer.component.html'
})
export class ArrayDisplayerComponent {
    constructor(public arrayManagerService: ArrayManagerService) {}
}

array-displayer.component.html

<div id="array-container">
    <div class="item" *ngFor="let item of arrayManagerService.arrayDynamic">
        {{item.name}}
    </div>
</div>

我想知道这是否是一种可接受的方式(主要涉及性能),还是应该在array-displayer.component.ts中声明一个数组,并在每次更新数组时使用EventEmiter对其进行更新。

angular performance ngfor
1个回答
1
投票

我认为从您的服务中,您应该返回一个可观察的对象,而您的组件则必须继续监听它:

    @Injectable()
    export class ArrayManagerService {
        public arrayDynamic = [];
        public bSubject$ = new BehaviourSubject(this.arrayDynamic);
        // some functions calling the api to update dynamic data
        setData(a){
     this.arrayDynamic.push(a);
     this.bSubject$.next(this.arrayDynamic);
         }
    }



export class ArrayDisplayerComponent implements OnInit {
    constructor(public arrayManagerService: ArrayManagerService) {}
   ngOnInit(){
    this.arrayManagerService.bSubject$.subscribe(arrData => {
     //this.yourArray = arrData;
   });

   }

}

© www.soinside.com 2019 - 2024. All rights reserved.