简体   繁体   English

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

[英]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; 当我尝试将数据发送到变量dataStr ,然后在应用程序组件中进行console print ,它返回undefined; How can I pass data from home component to app component? 如何将数据从家庭组件传递到应用程序组件?

app.component.ts 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 app.component.html

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

home.component.ts 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 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 事件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() providers[]数组中,如下所示:

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

now add following code in your home.component.ts , dont forget to import service 现在在您的home.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();
  }

now add this following code to your app.component.ts , don't forget to import service. 现在,将以下代码添加到您的app.component.ts中 ,不要忘记导入服务。

constructor(private _eventEmiter: EventEmiterService) {
  }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从父组件到子组件发射数据[Angular 2] - How to emit data from parent to child component [Angular 2] 如何在 Angular 中从子组件向父组件发出多个事件? - how to emit multiple events from child to parent component in Angular? 如何从组件循环向主父角5发射事件 - How to emit event from component loop to main parent angular 5 将数据从模板组件发送到 ReactJs 组件 - Emit data from stencil component to ReactJs component 如何以角度从另一个组件销毁活动路由组件 - How to Destroy Active Routing Component from another component in angular 如何在 Angular 8 中隐藏 Header 组件的导航栏按钮? - How to hide the Navigation bar buttons of Header Component from routing in Angular 8? 如何将数据从父组件发送到特定的动态创建的子组件? - How to emit data from Parent Component to a specific Dynamically created Child Component? 如何在发射成功时处理从 service.ts 到 component.ts 的 socket.io 确认 Angular 8 - How to handle socket.io acknowledgement from service.ts to component.ts on emit success Angular 8 Angular2 Routing - 将数据从父组件传递到子子组件 - Angular2 Routing - Passing data from parent component to a sub-child component Laravel 和 Vue 在 Blade 中将数据从组件 1 发送到组件 2 - Laravel and Vue emit data from component 1 to component 2 within Blade
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM