【发布时间】:2020-09-02 00:49:51
【问题描述】:
我的应用中有两个组件——“过滤器”和“主页”。这两个组件是 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() 之前将数据记录在服务中,而我实际获得的数据是我在 home 组件中更改的,这意味着我对 home 组件中的数据实例所做的更改也会影响(更改)服务中的数据。
filter.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();
}
}
我的控制台日志:
实际上应该是我刚刚在过滤器组件中传递的数据。但它显示了我在 home 组件中修改的数据。
最后是 app.component.ts,如果有帮助的话
app.component.ts
<app-filter></app-filter>
<app-home></app-home>
我想提请您注意的另一件事是。我试图在 stackblitz 中重新创建场景。但奇怪的是它在那里工作得很好。
https://stackblitz.com/edit/angular-ivy-9th5pj
请解释我的项目中缺少什么。或者这是服务将以角度工作的实际方式。
【问题讨论】:
-
你的真实代码中可能有一些不同的东西。您可能以某种方式多次致电
this.filterService.setFilterConditions。您的控制台中真的只有 1 个日志输出吗? -
是的。我在控制台中只有一个日志。如果我不止一次调用 this.filterService.setFilterConditions,我至少会有不止一个日志。
-
在没有源代码的情况下很难解释为什么会发生这种情况...您是否尝试设置断点来理解流程?
标签: angular typescript angular7 angular-services behaviorsubject