如何将数据从组件发送到模块?

时间:2019-05-28 23:27:32

标签: angular angular-services

我有一个组件,其中有flagPerfil变量,我需要将此变量发送到我的模块。

我的服务

export class ListUserService {
    public flagPerfil = boolean;
    changeFlagPerfil() {
        console.log('EEE' + this.flagPerfil);
        this.flagPerfil ? this.flagPerfil = false : this.flagPerfil = true;
    }

组件类:

@Component({
    selector: 'app-list-user',
    templateUrl: './list-user.component.html',
    styleUrls: ['./list-user.component.scss'],
    providers: [ListUserService]
})
export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }

这是视图 list-user.component.html

<span *ngIf="!flagPerfil">
  <input type="button" id="usuarios" name="more" (click)="changeFlagPerfil()"
    value="Amigos">
</span>

我有一个模块,我想在模块中注入服务,因为 我需要FlagProfile变量

  @NgModule({
    imports: [
        IonicModule,
        CommonModule,
        FormsModule,
        RouterModule.forChild([{path: '', component: Tab1Page}])
    ],
    declarations: [Tab1Page, ListUserComponent, FriendsComponent]
})
export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        this.flagPerfil = listUserService.flagPerfil;
        console.log('FLAG', listUserService.flagPerfil);
    }
}

如何使用事件发射?

我需要模块自动听到该变量的变化

2 个答案:

答案 0 :(得分:2)

export class ListUserService {
    public flag$ = new Subject< boolean >();

}


export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        listUserService.$flags.subscribe((flag)=>{
           console.log('FLAG', flag;
           this.flagPerfil = flag;
      });

    }
}


export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }


    constructor(private listUserService: ListUserService) {

    }
    functionThatGetsCalledWhenTheFlagIsChanged(){
       this.listUserService.flags$.next(this.flagPerfil);

     }

}



答案 1 :(得分:1)

您可以将类型传递给主题,如this主题教程中所示,例如= new Subject<boolean>();

有人问了类似的问题here

更新:我已修复格式设置,这阻止了<boolean>的显示