简体   繁体   中英

Angular 2 how to emit data from routing component

When I try to emit data to variable dataStr and then I am console print in app component it returns undefined; How can I pass data from home component to app component?

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'main',
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

    public dataStr: string;

    setDataStr(dataStr) {
        console.log(dataStr);
    }
}

app.component.html

<router-outlet (dataStr)="setDataStr($event)"></router-outlet>

home.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'home-page',
    template: `<h1>Test</h1>`
})
export class HomeComponent implements OnInit {

    @Output()
    dataStr = new EventEmitter();

    ngOnInit() {
        this.dataStr.emit('Test');
    }
}

app-routing.module.ts

import { NgModule }     from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './pages/home.component';

const routes: Routes = [
    { path: '', redirectTo: 'ka/home', pathMatch: 'full' },
    {
        path: 'ka',
        data: { lang: 'ka'},
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent, data: { lang: 'ka'} }
        ]
    },
    {
        path: 'en',
        data: { lang: 'en'},
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent, data: { lang: 'en'} }
        ]
    },
];


@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule {}

first of all you need to create service:

event-emitter.service.ts

import {Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class EventEmiterService {

  dataStr = new EventEmitter();

  constructor() { }

  sendMessage(data: string) {
    this.dataStr.emit(data);
  }
}

now import that service in providers[] array of NgModule() like this:

 @NgModule({
  declarations: [...],
  imports: [..],
  providers: [EventEmiterService],
  bootstrap: [AppComponent]
})

now add following code in your home.component.ts , dont forget to import service

sub: Subscription;

constructor(private _eventEmiter: EventEmiterService, private router: Router) {


  ngOnInit() {
   this.sub = this.router
      .data
      .subscribe(v => {
          console.log(v);
          this._eventEmitter.sendMessage(v)
       });

  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

now add this following code to your app.component.ts , don't forget to import service.

constructor(private _eventEmiter: EventEmiterService) {
  }

  setDataStr() {
    this._eventEmiter.dataStr.subscribe(data => console.log(data))
  }

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