
[英]share service data b/w two component in angular 2 using get set method
[英]Share data between components using Service - IONIC 2, Angular 2
是否可以使用一种方法将数据{{error.value}}
发送到另一页?
这是我的代码
<ion-row *ngFor="let errors of adp_principal_menuRS"> <ion-col class="info-col" col-4> <button ion-button color="primary" small (click)="goToErrors(errors.event)"> {{errors.event}} </button> </ion-col> </ion-row>
goToErrors(menu: string){ console.log(menu); this.navCtrl.push(AdpDetailPage, { }); }
我想将{{errors.event}}
值发送到goToErrors()
方法中的另一个页面。
谢谢!
编辑:我只是实现我想要的。 我编辑了代码
可以使用BehaviorSubject
通过服务在组件之间共享数据。 这是一个例子:
// service.ts
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class ShareService {
private errorSource = new BehaviorSubject<any>(null);
error$ = this.errorSource.asObservable();
setError(error: any){
this.errorSource.next(error);
}
设置error event
在parent component
使用setError
方法和订阅的error
在error component
。
// error component.ts
constructor(share: ShareService) {
share.error$.subscribe(Err => this.error = Err);
使用事件发射器。
//Home component.ts import { Events } from 'ionic-angular'; constructor(public events: Events) {} directioChange(user) {this.events.publish('directiochanged', 'true');} //App.component.ts constructor(public events: Events) { events.subscribe('directiochanged', (direction) => { this.isRtl = direction;console.log(direction);});}
我生成了一个Plunker,希望它与您要尝试的操作相匹配。
https://plnkr.co/edit/MNqpIqJjp5FN30bJd0RB?p=预览
服务
import { Injectable } from '@angular/core';
@Injectable()
export class ErrorService {
errorInfo: string;
}
零件
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<button (click)="goToErrors()">{{errors.event}} </button>
<router-outlet></router-outlet>
</div>
`,
})
export class App {
name:string;
errors = { event: 'Test Error', otherInfo: 'Test Info' };
constructor(private errorService: ErrorService, private router: Router) {
this.name = `Angular! v${VERSION.full}`
}
goToErrors(): void {
// Code to navigate to the other component
this.errorService.errorInfo = this.errors.event;
this.router.navigate(['/a']);
}
}
为什么不使用navParam发送值?
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
errorEvent: menu // <------------------------- Add this line
});
}
在您的AdpDetailPage
:
export class AdpDetailPage{
constructor(public navParams: NavParams){
errorEvent = this.navParams.get('errorEvent');
console.log("errorEvent= ", errorEvent);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.