Это, как я знаю. Пожалуйста, ищите больше ... Во-первых, вы должны создать подобный сервис и создать новый BehaviorSubject,
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InitialService {
value = new BehaviorSubject<string>(null);
constructor() { }
setValue(inputValue) {
this.value.next(inputValue);
}
getValue(): Observable<string> {
return this.value.asObservable();
}
}
, затем вы можете создать родительский component.ts как этот (учтите, что я использовал компонент приложения) ,
import { Component } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { InitialService } from './services/initial.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
value = new BehaviorSubject<string>(null);
constructor(private initialService: InitialService) { }
onClickMe(inputValue) {
this.initialService.setValue(inputValue);
}
getValue(): Observable<string> {
return this.value.asObservable();
}
}
Ваш родительский компонент. html,
<h1>Parent Component</h1>
<input #inputValue type="text">
<button (click)="onClickMe(inputValue.value)">Send to Child</button>
<app-child></app-child>
Ваш дочерний component.ts,
import { Component, OnInit } from '@angular/core';
import { InitialService} from '../../services/initial.service'
import { Observable } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
value: Observable<string>;
constructor(private initialservice: InitialService) {
this.value = initialservice.getValue();
}
ngOnInit() {
}
}
Ваш дочерний компонент html,
<h1>Child Component</h1>
<p>value: {{value | async}}</p>
если есть неясные вещи, дайте мне знать. Спасибо.