Angular 2如何从路由组件中发出数据

时间:2016-11-07 07:52:53

标签: javascript angular

当我尝试将数据发布到变量console print然后我在应用程序组件中undefined;时,它返回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.ts

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

app.component.html

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');
    }
}

home.component.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 {}

APP-routing.module.ts

this

1 个答案:

答案 0 :(得分:5)

首先,您需要创建服务:

<强>事件emitter.service.ts

现在在import {Injectable, EventEmitter} from '@angular/core'; @Injectable() export class EventEmiterService { dataStr = new EventEmitter(); constructor() { } sendMessage(data: string) { this.dataStr.emit(data); } } providers[]数组中导入该服务,如下所示:

NgModule()

现在在 home.component.ts 中添加以下代码,别忘了导入服务

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

现在将以下代码添加到 app.component.ts ,不要忘记导入服务。

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