-1

我正在尝试将所选项目的列表从一个组件共享到另一个组件。我创建了一个服务来声明列表:

  public selectedTasksToUnassign = [];

然后在这个组件中我尝试设置列表值:

组件_1.ts

checkTask(task) {
if (task) {
  if (this.selectedTasks.includes(task)) {
    this.selectedTasks.splice(this.selectedTasks.indexOf(task), 1);
  } else {
    this.selectedTasks.push(task);
  }
} else {
  if (this.selectedTasks.length < this.tasks.length) {
    this.selectedTasks = [];
    Array.prototype.push.apply(this.selectedTasks, this.tasks);
  } else {
    this.selectedTasks = [];
  }
}
this.tasksToSelect.emit(this.selectedTasks);
this.formService.selectedTasksToUnassign=this.selectedTasks;
console.log("task to unassign from table", this.formService.selectedTasksToUnassign);
  }

在这个组件中,我想获取列表: component_2.ts

 ngOnInit() {
console.log("test tasks to unassign",this.formService.selectedTasksToUnassign);
 }

事实上,我看到每次我检查表中的项目时,liste 都会在component_1.ts中的 console.log 中更新,并且我看到值已添加但在component_2.ts中的 console.log 中,它只显示第一个价值选择!!!

4

2 回答 2

2

这是因为服务使用的是常规值。如果您希望在每次更改时更新值。您需要使用 observables 来保存该值。

然后在component_2.ts中,你将订阅该值

共享服务

  public selectedTasksToUnassignSubject = new Behaviour Subject<Array<Tasks>>([]);

这将保持selectedTasksToUnassignSubject行为主体内部的值。任何想要读取它的值的组件都可以订阅它。因此,每当行为主题更新时,所有订阅者都会更新。

更新组件 1 内的行为主题

service.selectedTasksToUnassignSubject.next(tasks);

订阅行为主体的价值

service.selectedTasksToUnassignSubject.subscribe(data=>{
//Code To Run Whenever the value of task changes
})

我可以想象会rxjs变得相当混乱,特别是如果你刚开始使用 Angular。但是它们非常有用,一旦您了解它们的工作原理,您就会爱上它们。

于 2021-07-19T14:58:25.600 回答
1

那是因为(我假设)您checkTask()每次与任务列表交互时都会调用。因为checkTask()包含console.log,所以您会在 component_1 中的每次交互中看到它。

但是,在 component_2 上,您有一个console.logon ngOnInit()which 在组件加载时只运行一次。这就是为什么你只看到第一个console.log

如果你绑定formService.selectedTaskToUnassign到 component_2 的模板,你会看到每次 component_1 改变它的值时它都会更新。

component_2.component.ts

// Assuming that a task is a string
public tasksToUnassign: string[];

// Setup a local reference to the service property inside your constructor
constructor(private formService:FormService){
  this.tasksToUnassign = this.formService.selectedTasksToUnassign;
}

component_2.component.html

<ul>
  <!-- Use *ngFor to loop through each item of an array -->
  <li *ngFor="let task of tasksToUnassign">{{ task }}</li>
</ul>
于 2021-07-19T15:37:49.513 回答