2017-05-26 52 views
1

您好我需要将数据从一个组件传递到另一个组件,为此我使用了类BehavorSubject(我也试过Subject类,但不适用于我)。这是我的代码: 主页有一个过滤器,并选择过滤器时,它被称为服务和IT服务应该改变主页Angular 2:BehaviorSubject/Subject不能在构造函数外工作

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

尝试从组件元数据中移除提供者:[PatientService],并使用NgModule构造中定义的提供者。此外,我会重新考虑你如何设置TimeTime,Promise和Subject在一起。它看起来可以简化。 –

回答

0

最后我没有使用BehaviorSubject /主题的变化,我将过滤器中的数据传递到此主页:

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