使用服务在组件之间共享数据 - IONIC 2, Angular 2

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, {

    });
  }

我想在 goToErrors() 方法中将 {{errors.event}} 值发送到另一个页面。

谢谢!

编辑:我只是实现了我想要的。我编辑了代码

使用事件发射器。

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

可以通过服务在组件之间使用 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);
    }

使用setError方法设置parent component中的error event并订阅error component中的error

  // error component.ts
  constructor(share: ShareService) {
        share.error$.subscribe(Err => this.error = Err);

我生成了一个 Plunker,希望它能与您正在尝试做的事情相匹配。

https://plnkr.co/edit/MNqpIqJjp5FN30bJd0RB?p=preview

服务

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