html - 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
解决方案
推荐阅读
- algorithm - 如何从数据集进行模拟?
- javascript - 错误的偏移量();在火狐上
- variables - Orange3 Python 小部件我无法汇总标记为元的列的值
- .htaccess - htaccess 将所有页面和子目录指向 index.php
- javascript - DXP中的第三方js问题
- java - 如何将 JTextArea 字符串更改为其他内容
- c# - 有没有办法在 C# 中将自动生成的值(增量整数)赋予字典键值对中的值
- node.js - 格式错误的属性选择器 Cheerio
- arrays - 在数组中切换 UIbuttons 以选择/取消选择
- python - 带递归的帕斯卡三角