我一直在研究这个问题并尝试了所有方法,所以我做了一个非常基本的无法解决我需要的示例:
server.ts(提供程序从服务器获取数据)
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class ServerProvider {
basicUrl: any = "http://5.5.5.5/hotel/admin/api.php";
datos : any;
constructor(public http: HttpClient) {
console.log('Hello ServerProvider Provider');
}
getInfo() {
return this.http.get(this.basicUrl).subscribe(result=>{
this.datos = result;
});
}
}
tutorial.ts(将接收页面)
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ServerProvider } from "../../providers/server/server";
@IonicPage()
@Component({
selector: 'page-tutorial',
templateUrl: 'tutorial.html',
})
export class TutorialPage {
titulo: any;
datos: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public serverP: ServerProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad TutorialPage');
this.datos = this.serverP.datos;
this.titulo = this.datos["titulo"];
}
}
tutorial.html(查看显示信息的地方)
<ion-content padding>
<p>{{titulo}}</p>
</ion-content>
我知道为什么这行不通,但是我无法使可观察对象对我或任何其他选择起作用。
每次调用server.ts getInfo()并解决它时,我都需要更新titulo变量。
答案 0 :(得分:2)
您应该使用rxjs创建一个主题,并使用 Subject 中的next()
方法发出该值。每当服务getInfo
调用时,datos$
主题都会发出该值。
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs'
@Injectable()
export class ServerProvider {
basicUrl: any = "http://5.5.5.5/hotel/admin/api.php";
datos : any;
datos$ = new Subject<any>();
constructor(public http: HttpClient) {
console.log('Hello ServerProvider Provider');
}
getInfo() {
return this.http.get(this.basicUrl).subscribe(result=>{
this.datos = result;
this.datos$.next(this.datos);
});
}
}
您应该在component.ts中订阅datos$
,并将其发出的值更新为this.titulo
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ServerProvider } from "../../providers/server/server";
@IonicPage()
@Component({
selector: 'page-tutorial',
templateUrl: 'tutorial.html',
})
export class TutorialPage {
titulo: any;
datos: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public serverP: ServerProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad TutorialPage');
this.serverP.datos$.subscribe(value => this.titulo = value["titulo"]);
}
}
答案 1 :(得分:2)
在我的头上,将datos定义为Subject<any>
。然后,每当进行更新时,都调用datos.next
。在您的组件中,您开始使用ngOnint
收听subscribe
中的更新。每次调用Subscribe
时都会调用next
,因此您只需要执行一次即可。
您的代码应如下所示: server.ts
datos : new Subject<any>();
..
return this.http.get(this.basicUrl).subscribe(result=>{
this.datos.next(result);
});
tutorial.ts
export class TutorialPage implements OnInit {
titulo: any;
datos: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public serverP: ServerProvider) {
}
ngOnInit() {
this.serverP.datos.subscribe((datos) => this.titulo = this.datos["titulo"]);
}
..