Просто создайте свойство @Input
для вашего ребенка и передайте значение, которое вы хотите, используя синтаксис привязки свойства.Примерно так:
ChildComponent
Класс:
import { Component, OnInit, Input } from '@angular/core';
@Component({...})
export class ChildComponent implements OnInit {
@Input() childProperty;
}
ParentComponent
HTML:
<app-child [childProperty]="childProperty"></app-child>
ParentComponent
Класс:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({...})
export class AppComponent {
childProperty = {
foo: 'bar'
};
constructor(private http: HttpClient) {}
ngOnInit() {}
ngAfterViewInit() {
this.http.get('https://jsonplaceholder.typicode.com/todos/1')
.subscribe(user => this.childProperty = user);
}
}
Вот вам Рабочий образец StackBlitz для вашей ссылки.
ПРИМЕЧАНИЕ: Вы должны увидеть очень слабый переворот на виде, поскольку значения изменились.Но все изменится без проблем.
ОБНОВЛЕНИЕ
Вы также можете использовать SharedService
для обмена данными между этими двумя компонентами.В идеале, поскольку между этими двумя компонентами существуют отношения родитель-потомок, это не имеет особого смысла.Но поскольку вы уже пошли по этому пути, давайте исправим проблему под рукой.
Так что ваш SharedService
будет выглядеть примерно так:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class SharedService {
private sharedData: BehaviorSubject<any> = new BehaviorSubject<any>({});
sharedData$: Observable<any> = this.sharedData.asObservable();
constructor() { }
updateSharedData(updatedData) {
this.sharedData.next(updatedData);
}
}
Вы можете передать некоторые данные из вашегоParentComponent
, вызвав updateSharedData
на SharedService:
...
import { SharedService } from './shared.service';
@Component({...})
export class AppComponent {
...
anotherPropertyForChild = {
anotherKey: 'Another Value'
};
constructor(
...,
private shared: SharedService
) {}
ngOnInit() {
this.shared.updateSharedData(this.anotherPropertyForChild);
}
ngAfterViewInit() {
...
// Something like this:
this.http.get('https://jsonplaceholder.typicode.com/posts/1')
.subscribe(post => this.shared.updateSharedData(post));
}
}
А затем в вашем ChildComponent:
import { Component, OnInit, Input } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({...})
export class ChildComponent implements OnInit {
...
anotherChildProperty: any;
constructor(private shared: SharedService) { }
ngOnInit() {
this.shared.sharedData$.subscribe(
sharedData => this.anotherChildProperty = sharedData
);
}
}
Я также обновил Stackblitz этой реализацией.
Надеюсь, это приведет вас туда, куда вы хотите.