首页 > 解决方案 > Angular View 在更改另一个视图的值时更新

问题描述

我陷入了这样一种情况,即当我更新服务中定义的属性的值并且有两个服务实例时,因此在一个实例中更改属性会在另一个实例中更改。

我的服务.ts:

import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
  myData = Array<SomeInterfaceModel> = [];
  isView1: boolean;

  someMethod() {
   if(view1) {
   // Execute this
    } else {
       //Execute this
    }
  }

someInterfaceModel.ts:

{
isValid: boolean,
name: string
}

myModule.ts: 提供者为:

providers:[
{ provide: 'view1', useClass: myService },
{ provide: 'view2', useClass: myService }
]

我的组件.ts:

service: MyService;
@Input() isView1: boolean;
@Output() view1loaded = new EventEmitter<boolean>();

constructor(
@Inject('view1') private view1Service: MyService,
@Inject('view2') private view2Service: MyService
){}
ngOninit() {
  if(isView1) {
service = view1Service;
} else {
service = view2Service;
}

if(this.isview1) {
this.service.myData = [{isValid: true, name: "ABC"},{isValid: false: name: "XYZ"},{isValid: true, name: "MNO"}];
this.service.isView1 = true
this.view1loaded.emit(true);
} else {
this.service.myData = Object.assign([], this.view1Service.myData.filter(x => x.isValid));
this.service.isView1= false;
}

// This search is returns data as SomeInterfaceModel
onSearch(value) {
this.service.myData = value;
}
}

我的组件.html

<app-search-bar [searchList]="service.myData"
    (changedSearchListEmit)="onSearch($event)"></app-search-bar>

<div *ngFor="let data of service.myData">
<p>{{data.name}}</p>
</div>

app.component.html

<button (click)="isView1 === true">
    View1
  </button>
<div [hidden]="!isView1">
<app-my-component [isView1]="true" (view1Loaded)="onLoad($event)">
</app-my-component>
</div>

<div *ngIf="isView1Loaded">
<button (click)="isView1 === false">
    View1
  </button>    
<div [hidden]="isView1">
<app-my-component [isView1]="false">
</app-my-component>
</div>
</div>

app.component.ts:

isView1Loaded: boolean = false;
isView1:boolean = true;

onLoad(event) {
 if(event) {
this.isView1Loaded = true;
}
}

当我使用搜索时出现问题,我根据 myComponent.html 中的名称进行搜索,我得到正确的搜索输出并分配给 myData。但是数据的变化也反映到了其他视图,也就是 view2。虽然从 view2 搜索列表没有被修改为 view1

标签: htmlangulartypescript

解决方案


推荐阅读