这是我知道的。请搜索更多...
首先,你必须创建一个这样的服务并创建新的 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(考虑我使用了app组件),
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>
你的子组件.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>
如果有不清楚的地方,请告诉我。谢谢。