13 November 2018

Rxjs event click giữa hai components không có mối liên hệ Angular 2+

Rxjs Event Click
Hai components không có mối liên hệ 
app.component.html
Angular 2+
<first-app></first-app>

<second-app></second-app>
first.component.ts
Angular 2+
import { Component } from '@angular/core';
import { Service } from '../event.service';

@Component({
  selector: 'first-app',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent {

  flag: boolean = false;

  constructor(private service: Service) { }

  onSubmit(event: any) {
    this.service.newEvent(this.flag = !this.flag);
  }
}
second.component.ts
Angular 2+
import { Component } from '@angular/core';
import { Service } from '../event.service';

@Component({
  selector: 'second-app',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent {

  content: string = '';

  constructor(private service: Service) {
    this.service.responseEvent.forEach(event => this.content = event);
  }

}
event.service.ts
Angular 2+
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class Service {
    private subject = new Subject < any > ();
    //private subject = new BehaviorSubject<boolean>(false);

    newEvent(event) {
        this.subject.next(event);
    }

    get responseEvent() {
        return this.subject.asObservable();
    }
}
app.module.ts
Angular 2+
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';
import { Service } from './event.service';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent , FirstComponent, SecondComponent],
  bootstrap:    [ AppComponent ],
  providers: [Service]
})
export class AppModule { }



0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang