简体   繁体   中英

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.

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

<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

  @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?

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

A similar question was asked here

Update: I fixed the formatting, which was preventing <boolean> from being displayed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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