gpt4 book ai didi

Angular 7 : Service instance working incorrectly

转载 作者:行者123 更新时间:2023-12-03 23:07:07 25 4
gpt4 key购买 nike

我的应用程序中有两个组件 - 'filter' 和 'home'。这两个组件是 app 组件的子组件。

我有一个下面的对象,我想通过服务从过滤器组件传递到主组件。由于我希望此数据在过滤器组件中发生更改时在主组件中更新,因此我在服务中使用 BehaviorSubject。

模型:filter-response.model.ts

export interface FilterResponse{
filter:string;
filterlist:string[];
}

filter.component.ts
export class FilterComponent implements OnInit {
filterMainList:FilterResponse[]=[
{
"filter": "abc",
"filterlist": ["a","b","c"]
},
{
"filter": "def",
"filterlist":["d","e","f"]
},
{
"filter": "ghi",
"filterlist": ["g","h","i"]
}
];
constructor(private filterService:FilterService,) {
this.filterService.setFilterConditions(this.filterMainList);
}
ngOnInit() {
}
}

在 home 组件中,我收到了数据,我想对其进行一些更改。

home.component.ts
export class HomeComponent implements OnInit {
constructor(private filterService:FilterService) {
this.filterService.getFilterConditions().subscribe((data)=>{
let tc:FilterResponse[]=data
for(let f in tc){
tc[f].filterlist=['changes'];//this is where I make the changes
}
});
}
ngOnInit() {
}
}

我有一个过滤服务,它有行为主题。这是我感到困惑的地方。我在 next() 之前将这里的数据记录在 service 中,而我在这里实际得到的数据是我在 home 组件中更改的数据,这意味着我对 home 组件中的数据实例所做的更改也影响(更改)了服务中的数据。

过滤器.service.ts
@Injectable({
providedIn:'root'
})
export class FilterService{
private filterConditions = new BehaviorSubject<FilterResponse[]>(null);
constructor(){}
setFilterConditions(filterList:FilterResponse[]){
console.log(filterList);//data changes incorrectly
this.filterConditions.next(filterList);
}
getFilterConditions():Observable<FilterResponse[]>{
return this.filterConditions.asObservable();
}
}

我的控制台日志:

console log

实际上应该是我刚刚在过滤器组件中传递的数据。但它显示了我在 home 组件中修改的数据。

最后是 app.component.ts,如果有帮助的话

app.component.ts
<app-filter></app-filter>
<app-home></app-home>

我想提请您注意的另一件事是。我试图在 stackblitz 中重新创建场景。但扭曲的是它在那里工作正常。

https://stackblitz.com/edit/angular-ivy-9th5pj

请解释我在我的项目中缺少什么。或者这是服务以 Angular 工作的实际方式。

最佳答案

在您的服务文件中进行此更改

 setFilterConditions(filterList:FilterResponse[]){
this.filterConditions.next(JSON.parse(JSON.stringify(filterList)));
}

这将克隆您的阵列。还有许多其他方法可以在 JS 中克隆对象/数组
Different ways to Clone object in JS

原因 :

在 TS 中,当将对象作为函数参数传递时,您传递的是对该对象的引用。因此,当修改传递给函数的对象时,您正在修改该原始对象。

类似地,在 HomeComponent 的订阅函数中接收的数组/对象是通过引用接收的。所以 HomeComponent 中的值变化也会在服务中受到影响。

关于 Angular 7 : Service instance working incorrectly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com