简体   繁体   English

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

[英]How send data from a component to a Module?

I have a component where I have flagPerfil variable, I need to send this variable to my module. 我有一个组件,我有flagPerfil变量,我需要将此变量发送到我的模块。

my service 我的服务

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

component class: 组件类:

@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;
    }

This is the view list-user.component.html 这是视图list-user.component.html

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

I have a module, I want to inject the service in the module, because I need the FlagProfile variable 我有一个模块,我想在模块中注入服务,因为我需要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);
    }
}

How do I use an event Emit? 我如何使用事件Emit?

I need the module to automatically hear the changes of that variable 我需要模块自动听到该变量的变化

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);

     }

}



You can pass the type to the Subject as shown in this tutorial for Subject, eg = new Subject<boolean>(); 您可以将类型传递给Subject,如教程中针对Subject所示,例如= new Subject<boolean>();

A similar question was asked here 这里也提出类似的问题

Update: I fixed the formatting, which was preventing <boolean> from being displayed 更新:我修复了格式化,这阻止了<boolean>显示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM