How to detect change from one component into other

前端 未结 2 429
甜味超标
甜味超标 2021-02-09 06:48

Angular 4. Github source

I have a menu which is filled by a web service. The web service is in taskService, but is not necessary now.

ngOnInit() {
             


        
2条回答
  •  眼角桃花
    2021-02-09 06:58

    Angular isn't running changeDetection because you aren't asking it to. None of the instance variables in your ViewTaskComponent are being updated inside your save method.

    In your code, after updateTask() finishes, it returns to save() in your ViewTaskComponent. But there is no link to this.task in the subscription callback to this.taskService.updateTask().

    Since updateTask uses a PATCH request, I'm assuming you're not getting the whole Task object back. So you won't be able to just say this.task = valuePassedToSubscribeCallback.

    Instead you can invoke this.viewTask() in that subscribe callback and fetch the entire updated Task object.

    For example:

    this.taskService.updateTask(task, id)
        .subscribe(
            // new line here to fetch the updated Task object
            this.viewTask()
        );
    

    Note: I'd second @Bunyamin Coskuner's suggestion to utilize BehaviorSubject's (or even a standard Subject). If you're up for a refactor, they are a clean way to manage state within your services.

提交回复
热议问题