Answer the question
In order to leave comments, you need to log in
Angular 2. How to organize interaction between components through a service?
It is necessary to organize the interaction between components in Angular 2. I do it according to the documentation .
Root component app.component.ts:
import { Component } from '@angular/core';
import {TestComponent} from './test/test.component';
import {ButtonComponent} from './button/button.component';
@Component({
selector: 'my-app',
directives: [TestComponent, ButtonComponent],
template: `<h1>My First Angular 2 App</h1>
<my-test></my-test>
<my-button></my-button>`
})
export class AppComponent { }
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { SendService } from '../send/send.service';
@Component({
selector: 'my-test',
providers: [SendService],
template: `<div>Message:</div>
<div>{{message}}</div>
`,
})
export class TestComponent implements OnDestroy{
message: string = 'test';
subscription: Subscription;
constructor(private sendService: SendService) {
this.subscription = sendService.message$.subscribe(
message => {
this.message = message;
console.log(`Message: '${message}'`)
});
}
ngOnDestroy(){
this.subscription.unsubscribe();
}
}
import { Component } from '@angular/core';
import { SendService } from '../send/send.service';
@Component({
selector: 'my-button',
providers: [SendService],
template: `
<button type="submit" (click)="submit()">Submit</button>
`,
})
export class ButtonComponent {
constructor(private sendService: SendService){}
submit(){
console.log('Button pressed');
this.sendService.sendMessage('My message');
}
}
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SendService {
// Observable string sources
private messageSource = new Subject<string>();
// Observable string streams
message$ = this.messageSource.asObservable();
// Service message commands
sendMessage(message: string) {
this.messageSource.next(message);
console.log(`run sendMessage('${message}')`);
}
}
button.component.ts:16 Button pressed
send.service.ts:13 run sendMessage('My message')
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question