简体   繁体   English

在Angular 2中的两个组件(页面)之间传递值

[英]Passing value between two components (pages) in Angular 2

I am using Angular 2 (TypeScript) 我正在使用Angular 2(TypeScript)

I have two components (actually they are two pages too). 我有两个组件(实际上它们也是两个页面)。 They are NOT parent and child relationship. 他们不是父母和孩子的关系。

I want to pass a value to second component(page) when I click the link in the first component(page). 当我单击第一个组件(页面)中的链接时,我想将值传递给第二个组件(页面)。

I know "URL parameters" way through router. 我通过路由器知道“URL参数”的方式。 But I don't want to show this parameter in the link. 但我不想在链接中显示此参数。 Is there any other way? 还有其他方法吗?

Thank you! 谢谢!

The canonical way is to establish an injectable service and inject the service into any components that need the data. 规范方法是建立injectable注入服务并将服务注入到需要数据的任何组件中。 Since the service is a singleton, the components will be accessing the same data. 由于服务是单例,因此组件将访问相同的数据。 It shouldn't matter that they are on different pages. 它们在不同的页面上并不重要。 Plunker here . 这里的人物

Edit: Here's a more involved example that shows two-way communication between components by subscribing to an eventEmitter on a service: Plunker 编辑:这是一个更为复杂的示例,通过订阅服务上的eventEmitter来显示组件之间的双向通信: Plunker

import {Component, Injectable} from 'angular2/core'

// your shared service 
// provide reference in parent component or bootstrap 
@Injectable()
export class myService {
  sharedData:string = "String from myService"
}

@Component({
  selector: 'page1',
  providers: [],
  template: `
    <div>
      <b>Component Page1 - shared data:</b> {{SharedData}}
    </div>
  `,
  directives: [],
})
export class Page1 {
  constructor(aService: myService) {
    this.SharedData = aService.sharedData
  }
}

@Component({
  selector: 'page2',
  providers: [],
  template: `
    <div>
      <b>Component Page2 - shared data:</b> {{SharedData}}
    </div>
  `,
  directives: [],
})
export class Page2 {
  constructor(aService: myService) {
    this.SharedData = aService.sharedData
  }
}

Thank you MarkM! 谢谢MarkM! It works, but it has been difficult for me because I have it all in diferent files and over last angular2 using angular cli... So I explain it here: 它有效,但对我来说很难,因为我把它全部放在不同的文件中,而且使用了角度cli的最后一个angular2 ...所以我在这里解释一下:

First of all: You need to create a file with the class you want to share with other components: data.service.ts and make it "@Injectable": 首先:您需要创建一个文件,其中包含您要与其他组件共享的类: data.service.ts并将其设为“@Injectable”:

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

@Injectable()
export class myService {
  public sharedData:string;

  constructor(){
    this.sharedData = "String from myService";
  }

  setData (data) {
    this.sharedData = data;
  }
  getData () {
    return this.sharedData;
  }
}

Make sure you set the created class (myService) on 'providers' only once on the app.module.ts file and import the injectable file: data.service.ts : 确保在app.module.ts文件中仅在'providers'上设置创建的类(myService)并导入可注入文件: data.service.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { routing, appRoutingProviders } from './app.routing';
import { AppComponent } from './app.component';
import { AppContent } from './components/content.component';
import { AppInsertContent } from './components/insert.component';
import { myService } from './services/data.service';

@NgModule({
  declarations: [
    AppComponent,
    AppContent,
    AppInsertContent,
  ],
  imports: [
    BrowserModule,
    routing
  ],
  providers: [appRoutingProviders, myService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Wherever you want to use your shared class use the constructor to create an object from the class (this object will be unique for your components, thanks to the @Injectable decorator). 无论你想在哪里使用你的共享类,都要使用构造函数从类中创建一个对象(由于@Injectable装饰器,这个对象对你的组件来说是唯一的)。 Remember to import it on every file you use it!... 记得在你使用它的每个文件上导入它!...

In my case this view sets the data of the object with a text input: input.component.ts 在我的例子中,此视图使用文本输入设置对象的数据: input.component.ts

import { Component } from '@angular/core';
import { myService } from '../services/data.service';

@Component({
  selector: 'insert-content',
  template: `
   <input id="textbox" #textbox type="text">
   <button (click)="this._myService.setData(textbox.value); SharedData = textbox.value;">SAVE</button>
   Object data: {{SharedData}}

    <div class="full-button">
      <a routerLink="/" routerLinkActive="active">BACK</a>
    </div>
  `
})

export class AppInsertContent {
  SharedData: string;
  constructor (private _myService: myService){
    console.log(this._myService.getData());
  }
}

And in this view I just see the data that has been set on the object: content.component.ts 在这个视图中,我只看到对象上设置的数据: content.component.ts

import { Component } from '@angular/core';
import { myService } from '../services/data.service';

@Component({
  selector: 'app-content',
  template: `
  <div style="float:left; clear:both;"> 
    {{_myService.getData()}} 
  </div>

  <div class="full-button">
    <a routerLink="/insert" routerLinkActive="active">INSERT</a>
  </div>
  `
})
export class AppContent {
  constructor (private _myService: myService){
    console.log(this._myService.getData());
  }
}

I hope this info is usefull! 我希望这些信息有用!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM