ionic2プロジェクトを開発している間に新しいプロバイダーを作成しましたが、MyClassで変数を設定する際にいくつかの問題があります。Ionic2:プロバイダーを扱います
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MyClass {
token_acces: any;
token_room: any;
constructor(private http: Http) {
this.token_acces = null;
this.token_room = null;
}
login(id,pwd){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('/localhost/',
JSON.stringify({
username: id ,
password: pwd
}), {headers : headers})
.map(res => res.json())
.subscribe(data=>{
this.token_acces = data;
});
}
getToken(){
return this.token_acces;
}
}
主な問題はlogin()
私はgetToken()
を呼び出すときnull
あるtoken_access
設定されていないということです。
さらに、私の疑問を持っています。このプロバイダは私のアプリのすべてのページで使用されています。 は、例えばホームページが含まれています
export class SearchPage {
token: any;
constructor(public navCtrl: NavController, public myClassService: MyClass) { }
...
が、私は同じインスタンスを使用するか、それはMyClassのの異なるistanceですので、アイ・アム:
...
export class HomePage {
id: any;
pwd: any;
constructor(public navCtrl: NavController, public myClassService: MyClass) { }
login(): void{
this.myClassService.login(this.id, this.pwd);
this.navCtrl.push(SearchPage, { token : this.myClassService.getToken()});
}
}
私には、例えば、他のページと同じことを行う場合前のページで設定された値を取得できませんか?あなたのコードのMyClassので
プロバイダが 'ngModule'で宣言されている場合は、同じインスタンスを使用します。トークンを受信しない場合、http呼び出しは非同期であり、まだ値を設定していない可能性があります。 –
ボタンを押すと、新しいページが読み込まれてプロバイダから値が取得されても、プロバイダとhttp.postを実行しますが、まだ設定されていません。 http.postで処理が完了するまではどうすればいいですか? – pittuzzo
プロバイダーのhttpポストにObservableを作成します。 Observableを呼び出し側のクラス/メソッドに戻します。このクラスをCallingクラスでObservableに登録する。さて、クラスを呼び出すときに、あなたが 'subscribe()'で何をする必要があれば何でもしてください。 http://stackoverflow.com/questions/42160061/ionic-2-login-component-and-auth-service –