[英]Passing value between two angular2 component typescript files
我有两个不是父组件和子组件的组件,但我需要将值从组件 A 传递到组件 B。
例子:
src/abc/cde/uij/componentA.ts 有变量 CustomerId = "ssss"
需要将该变量 customerID 传递给 src/abc/xyz/componentB.ts
简单的例子:
组件 A:
@Component({})
export class ComponentA {
constructor(private sharedService : SharedService) {}
sendMessage(msg : string) {
this.sharedService.send(msg);
}
}
组分 B:
@Component({})
export class ComponentB {
constructor(private sharedService : SharedService) {
this.sharedService.stream$.subscribe(this.receiveMessage.bind(this));
}
receiveMessage(msg : string) {
console.log(msg); // your message from component A
}
}
共享服务:
@Injectable()
export class SharedService {
private _stream$ = new Rx.BehaviorSubject("");
public stream$ = this._stream$.asObservable();
send(msg : string) {
this._stream$.next(msg);
}
}
共享服务必须放在同一个NgModule
。
在您的服务上定义一个setMyProperty()
和一个getMyProperty()
。 然后 setMyProperty 与来自组件 A 的值。 ComponentB 然后 getMyProperty 在那里您返回值...
您必须将服务注入到两个组件中。
你可以试一试。 它非常简单直接。
我只是按照这个例子进行了一些更改,以便它可以是兄弟姐妹而不是父母/孩子。
我的服务.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {
// Observable string sources
private myAnnouncedSource = new Subject<string>();
// Observable string streams
myAnnounced$ = this.myAnnouncedSource.asObservable();
// Service message commands
announceItem(item: string) {
this.myAnnouncedSource.next(item);
}
}
我的comp1.component.ts
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
@Component({
selector: 'my-compA',
template: `...`,
providers: [MyService]
})
export class MyComponentA {
constructor(private myService: MyService) {
}
announceToOtherComps() {
let sharedItem = "shibby";
this.myService.announceItem(sharedItem);
}
}
我的comp2.component.ts
import { Component, Input, OnDestroy } from '@angular/core';
import { MyService } from './my-service.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-compB',
template: `...`,
providers: [MyService]
})
export class MyComponentB implements OnDestroy {
sharedItem = '<no data>';
subscription: Subscription;
constructor(private myService: MyService) {
this.subscription = myService.myAnnounced$.subscribe(
item => {
this.sharedItem = item;
});
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
<component-a [id]="product.id"></component-a>
在组件-a ts 文件中。使用如下
export class ComponentA implements OnInit {
@Input() // <------------
id: number;
(...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.