Angular 5:订阅不会在下一个值上触发

时间:2017-11-14 16:18:12

标签: angular typescript rxjs

当向主题推送下一个值时,父组件中的订阅不会被触发(当我将主题更改为我无法使用的行为主题时会发生这种情况,因为有' s没有默认值。)

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>

我希望看到&#34; subOptions被解雇&#34;当我更改单选按钮的选择但在控制台中它只显示&#34;下一个句点:...&#34;。为什么它不起作用?

1 个答案:

答案 0 :(得分:0)

你不能像你一样注射组件。相反,您需要引用该组件并使用ViewChild(或ViewChildren)来选择它。

在模板中,您可以使用

<app-option #option [httpHeader]="httpHeader"></app-option>

然后,在句号组件中:

@ViewChild('option') option: OptionComponent;

如果您不想使用#option模板语法,您也可以根据组件类选择它:

@ViewChild(OptionComponent) option: OptionComponent;