简体   繁体   English

从服务中调用组件方法

[英]Call component method from service

I am completly new in angular. 我完全是新手。 I have 2 components, one for displaying list of taks, one for adding new one. 我有2个组件,一个用于显示任务列表,一个用于添加新组件。 They use one service. 他们使用一项服务。 This is my function in TasksComponent: 这是我在TasksComponent中的功能:

getTasks(): void {
  this.tasksService.getTasks()
                       .subscribe(
                           tasks => this.tasks = tasks,
                            err => {
                                console.log(err);
                            });
}

And I have also function for adding new Task in TasksInputFormComponent. 我还具有在TasksInputFormComponent中添加新Task的功能。 So I need to call getTasks() function from another component using shared service. 因此,我需要使用共享服务从另一个组件调用getTasks()函数。 I have found this question How to call component method from service? 我已经发现了这个问题, 如何从服务中调用组件方法? (angular2) and have tried to do something like in example. (angular2) ,并尝试执行类似示例中的操作。 I don't understand how to do it right. 我不知道该怎么做。 In tasksService: 在taskService中:

private componentMethodCallSource = new Subject<any>();
componentMethodCalled$ = this.componentMethodCallSource.asObservable();

In TasksComponent: 在TasksComponent中:

  constructor(private tasksService: TasksService) {
    this.tasksService.componentMethodCalled$.subscribe(
    () => {
      this.tasksService.getTasks()
                       .subscribe(
                           tasks => this.tasks = tasks,
                            err => {
                                console.log(err);
                            });
    }
  );

} }

In TasksInputFormComponent: 在TasksInputFormComponent中:

   addTask(task) {
    ...
    this.tasksService.addTask(...);
    this.tasksService.callComponentMethod();
  }

But this code looks absolutly strange and doesn't work. 但是这段代码看起来很奇怪,无法正常工作。 I can't find how to do it properly. 我找不到正确的方法。

If you want to call a component method from other component you can use ViewChild 如果要从其他组件调用组件方法,则可以使用ViewChild

@ViewChild(OtherComponent) otherCompt: OtherComponent

and access to method of OtherComponent, example 并访问OtherComponent的方法,例如

ngAfterViewInit() {
  this.otherCompt.methodX();
}

In your service: 为您服务:

    private tasksStreamer:Subject<Task[]> = new Subject();
    private tasks:Task[] = [];

    public addNewTask(task){
       this.tasks.push(task);
       this.tasksStreamer.next(this.tasks);
    }

    public getTasksStreamer():Subject<Task[]>{
       return this.tasksStreamer;
    }

AddTaskComponent: AddTaskComponent:

    this.myservice.addTask(task);

TasksComponent: TasksComponent:

    private myTasks:Task[] = [];
    this.myservice.getTasksStreamer()
        .subscribe(tasks => this.myTasks = tasks);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM