Angular 角度5:下一个值未触发订阅
当下一个值被推送到某个主题时,父组件中的订阅不会触发,当我将主题更改为无法使用的BehaviorSubject时,会触发订阅,因为没有默认值 option.component.ts periodeomzet.component.htmlAngular 角度5:下一个值未触发订阅,angular,typescript,rxjs,Angular,Typescript,Rxjs,当下一个值被推送到某个主题时,父组件中的订阅不会触发,当我将主题更改为无法使用的BehaviorSubject时,会触发订阅,因为没有默认值 option.component.ts periodeomzet.component.html 当我更改单选按钮的选择时,我希望看到控制台中触发的子选项,但它只显示下一个周期:。。。。为什么它不工作?您不能像现在这样注入组件。相反,您需要引用组件并使用ViewChild或ViewChildren来选择它 在模板中,可以使用 <app-option #
当我更改单选按钮的选择时,我希望看到控制台中触发的子选项,但它只显示下一个周期:。。。。为什么它不工作?您不能像现在这样注入组件。相反,您需要引用组件并使用ViewChild或ViewChildren来选择它 在模板中,可以使用
<app-option #option [httpHeader]="httpHeader"></app-option>
如果不想使用选项模板语法,也可以根据组件类选择它:
@ViewChild(OptionComponent) option: OptionComponent;
为什么您要通过DI访问子组件,而不是绑定到@Output或通过服务进行通信?我不确定为什么我要这样做,因为我是一个初学者。如果我让两个组件通过一个服务进行通信,那么如果我有多个组件对,它们如何与同一个服务实例通信?你能用@Output展示一个例子吗?你试过阅读文档吗?内疚:…@jornsharpe我已经实现了EventEmitter+@Output方法,这很有效。这对我来说是全新的,所以谢谢你指出这一点,谢谢。我在模板中添加了选项,添加了@ViewChild'option'选项:OptionComponent;在中的构造函数上方,并从TS中删除了提供程序,但无法读取属性“period”undefined@Rogier您是否也移除了Option组件的注入?我想是的。我从组件中删除了提供程序:[OptionComponent]decorator@Rogier你也从构造器中删除了它?
import { Component, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { httpService } from 'app/services/http.service';
import { OptionComponent } from 'app/units/option/option.component';
@Component({
selector: 'app-periodeomzet',
templateUrl: './periodeomzet.component.html',
providers: [OptionComponent]
})
export class PeriodeomzetComponent implements OnInit {
httpHeader: Object;
subData: Subscription;
subOptions: Subscription;
period: string = 'period=d';
constructor(
private httpService: httpService,
private option: OptionComponent
){}
getReport(){
this.subData = this.httpService.getReport().subscribe((res: Response) => {
this.httpHeader = res.json()['header'];
});
}
ngOnInit(){
this.subOptions = this.option.period.subscribe(period => {
console.log('subOptions subscription fired');
this.period = period;
this.getReport();
// Do other stuff
});
}
ngOnDestroy(){
this.subData.unsubscribe();
this.subOptions.unsubscribe();
}
}
<app-option [httpHeader]="httpHeader"></app-option>
<app-option #option [httpHeader]="httpHeader"></app-option>
@ViewChild('option') option: OptionComponent;
@ViewChild(OptionComponent) option: OptionComponent;