12 November 2018

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

Rxjs Bindding data
Hai components không có mối liên hệ 
bindding.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);

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

    get responseData() {
        return this.subject.asObservable();
    }
}
first.component.ts
Angular 2+
import { Component } from '@angular/core';
import { Service } from '../bindding.service';

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

  constructor(private service: Service) { }

  onKeypress(event: any) {
    this.service.sendData(event.target.value);
  }
}
second.component.ts
Angular 2+
import { Component } from '@angular/core';
import { Service } from '../bindding.service';

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

  content: string = '';

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

}
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-component/first.component';
import { SecondComponent } from './second-component/second.component';
import { Service } from './bindding.service';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent , FirstComponent, SecondComponent],
  bootstrap:    [ AppComponent ],
  providers: [Service]
})
export class AppModule { }
app.component.html
Angular 2+
<first-app></first-app>
<hr/>
<second-app></second-app>



0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang