При изменении значения директивы @Input внутри блока подписки в родительском компоненте изменения не обнаруживаются в дочернем компоненте - PullRequest
0 голосов
/ 17 января 2019

Я изменяю значение для одной директивы Input для моего дочернего компонента из родительского компонента внутри блока подписки. Однако новые значения не обнаружены в дочернем элементе.

Дочерний компонент уже реализует OnChanges и правильно определяет директивы ввода.

Ниже приведен псевдокод для моих компонентов. Это упрощено от фактического код для простоты понимания контекста.

РОДИТЕЛЬСКИЙ КОМПОНЕНТ HTML:

<h1>PARENT</h1>
<button (click)="buttonClicked()">NEXT</button>
<child-component  [inputChildVar]="parentValue"></child-component>

РОДИТЕЛЬСКИЙ КОМПОНЕНТ TS:

ngOnInit() {
    this.parentValue= {
      "currentPageNo":5,
      "currentPageData": [{"DEVICE":"Kernel1","RANGE":"500Hz"}, {"DEVICE":"Kernel2","RANGE":"500Hz"}]
    }
}

buttonClicked()
{
  this.parentService.ServiceMethod().subscribe(data=>{
     this.parentValue= {
        "currentPageNo":data.currentPageNo,
        "currentPageData":data.array
      }
     this.parentValue=JSON.parse(JSON.stringify(this.parentValue))
  })
}

КОМПОНЕНТ РЕБЕНКА HTML:

<h1>inputChildVar<h1>

ДЕТСКИЙ КОМПОНЕНТ TS:

import { Component, OnInit, Input,OnChanges } from '@angular/core';

@Component({ 
    selector: 'child-component', 
    template: '<h1>inputChildVar<h1>', 
})

export class ChildComponent implements OnInit,OnChanges 
{ 
    @Input() inputChildVar

    constructor() { } 
    ngOnChanges(){ 
        console.log(this.inputChildVar) 
    } 

    ngOnInit() {} 
}  

Ожидаемый результат: при получении ответа от parentService.ServiceMethod при изменении parentValue новые значения должны отображаться на экране через дочерний компонент.

Фактический результат: на экране нет изменений

Ответы [ 2 ]

0 голосов
/ 18 января 2019

Мне удалось решить проблему, запустив обнаружение изменений через changeDetectorRef.Теперь это работает.Получил ссылку от: Angular 2 - Вид не обновляется после изменения модели

0 голосов
/ 18 января 2019

Как я тестировал в StackBlitz, он отлично работает, посмотрите на:

Parent Component HTML * * 1004

<h1>PARENT</h1>
<button (click)="buttonClicked()">NEXT</button>
<app-child  [inputChildVar]="parentValue"></app-child>

Parent Component TS

import { Component } from '@angular/core';
import { DataService } from './data.service';

/** @title Simple form field */
@Component({
  selector: 'form-field-overview-example',
  templateUrl: 'form-field-overview-example.html',
  styleUrls: ['form-field-overview-example.css'],
  providers: [DataService]
})
export class FormFieldOverviewExample {

  constructor(private service: DataService) {

  }
  parentValue = {
    "userId": 112,
    "id": 1121,
    "title": "masxsat",
    "body": "teasdas"
  }
  buttonClicked() {
    this.service.getData()
    this.service.data.subscribe(value => {
      console.log(value)
      this.parentValue = value;
    })
  }
}

Child Component HTML:

<h1>Child</h1>
<div>
{{inputChildVar | json}}
</div>

Child Component TS:

import { Component, OnInit, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {

  @Input() inputChildVar

  constructor() { }
  ngOnChanges() {
    console.log(this.inputChildVar)
  }
  ngOnInit() { }
}

Data.Service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  data = new BehaviorSubject(null)

  constructor(
    private http: HttpClient
  ) { }


  getData() {
    this.get()
      .then(response => {
        this.data.next(response);
      })
  }

  get(): Promise<any> {
    const url = `https://jsonplaceholder.typicode.com/posts/1`;
    return this.http.get(url)
      .toPromise()
      .catch(this.handleError);
  }

  // handler for error in URL
  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}

StackBlitz

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...