【发布时间】:2017-11-14 16:18:12
【问题描述】:
当将下一个值推送到主题时,不会触发父组件中的订阅(当我将主题更改为我无法使用的 BehaviorSubject 时会触发,因为没有默认值)。
option.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'app-option',
templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
@Input() httpHeader;
period: Subject<string> = new Subject<string>();
constructor(){}
ngOnInit(){}
setPeriod(period: string){
this.period.next(period);
console.log('Next period: ' + period);
}
}
option.component.html
<mat-radio-group [(ngModel)]="periode" (ngModelChange)="setPeriod($event)">
<span *ngFor="let option of httpHeader.option"><mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button><br /></span>
</mat-radio-group>
父组件:
periodeomzet.component.ts
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();
}
}
periodeomzet.component.html
<app-option [httpHeader]="httpHeader"></app-option>
当我更改单选按钮的选择时,我希望在控制台中看到“子选项已触发”,但它只显示“下一个周期:...”。为什么它不起作用?
【问题讨论】:
-
为什么要通过 DI 访问子组件,而不是绑定到 @Output 或通过服务进行通信?
-
我不知道为什么我这样做,因为我是一个初学者。如果我让这两个组件通过服务进行通信,如果我有多个组件对,它们如何与服务的同一个实例通信?你能用@Output 举个例子吗?
-
您尝试阅读文档了吗? angular.io/guide/component-interaction
-
有罪:) ......
-
@jonrsharpe 我已经实现了 EventEmitter + @Output 方法并且可以工作。这对我来说是全新的,所以谢谢你指出这一点
标签: angular typescript rxjs