1

嗨,我需要将数据从一个组件传递到另一个组件,为此我使用的是 BehavorSubject 类(我也尝试过使用 Subject 类,但对我不起作用)。This is my code: Home page has a filter, and when is selected a filter, it called the service and it service should change a variable of homePage

HomePage.ts
@Component({
  providers: [PatientService],
})
export class HomePage {
   subscription: Subscription;
   constructor(  public auth: AuthService,
                public patientService: PatientService) {
      this.subscription = this.patientService.nameGiven.subscribe(
        nameGiven => {
          this.patientsByElement = nameGiven.toString();
      });
   ------ more code---
}

Filtro.ts
export class FiltroPage {
    showFilter(filter : FiltroT): void{
        ... code ...
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
            this.PatientService.getPatientsByTags(this.token,this.filterSelected);
        }  , 1000);
    }
}

patient-service.ts
import { Subject }    from 'rxjs/Subject';
import { Observable ,BehaviorSubject } from 'rxjs/Rx';
@Injectable()
export class PatientService {
    nameSource =  new BehaviorSubject("asd");
    nameGiven = this.nameSource.asObservable();
    this.nameSource.next('hi!!!');  //**it works but only in the constructor**
    this.nameGiven.subscribe(()=>{
       console.log("it changed");
    });

    getPatientsByTags(token: String, tags: Array<string>){
        return new Promise(resolve => {
            this.http.get(ConnectionParams.DevEnv + ProceduresNames.TagsByPatient + ProceduresNames.TagIdEtiqueta + tags, options)
            .map(res => res.json())
            .subscribe(data => {
              if(data.data.poAnicuRegistros){
                console.log("here")
                this.nameSource.next('hi TON :/');  // <-- ***here is the problem. It doesnt work***
              }
              else
                console.log("XX");
              resolve( this.data);
            });
        });
    }
}
4

1 回答 1

0

最后我没有使用 BehaviorSubject/Subject,我通过这种方式将数据从过滤器传递到主页:

HomePage.ts
public popoverCtrl: PopoverController
//code ...
showFilter(myEvent) {
    let popover = this.popoverCtrl.create(FiltroPage, {
      showConfirm: (x) => {
        //do something with the data received from the filter
      }
    });
    popover.present({
      ev: myEvent
    });

  }

Filter.ts
//code... 
params: NavParams;
showConfirm() {// function that return the data to homePage
        this.params.get('showConfirm')(this.patientsBytag);
    }
于 2017-06-30T15:14:48.300 回答