Ionic2:处理提供者 [英] Ionic2: handle a provider
问题描述
在开发ionic2项目时,我创建了一个新的提供程序,但是在MyClass中设置变量时遇到了一些困难。
While developing a ionic2 project, I created a new provider but I have some difficulties in setting variables in MyClass.
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()
未设置 token_access
这是 null
当我调用 getToken()
。
The main issue is that the login()
doesn't set the token_access
which is null
when I call the getToken()
.
此外我有疑问,所有页面都使用此提供程序在我的应用程序中
例如主页包含:
Moreover I have a doubt, this provider is used by all the pages in my app. For example the homepage contains:
...
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()});
}
}
如果我对其他页面执行相同操作,例如:
If I do the same with another page, for example:
export class SearchPage {
token: any;
constructor(public navCtrl: NavController, public myClassService: MyClass) { }
...
我是否使用相同的实例,或者它是MyClass的不同,因此我无法获得上一页中设置的值?
Am I using the same instance or it is a different istance of MyClass and so I can't get the values set in the previous page?
推荐答案
在你的代码的MyClass中:
In MyClass of your code:
login(id,pwd){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return Observable.create(observer => {
this.http.post('/localhost/', JSON.stringify({
username: id ,
password: pwd
}), {headers : headers})
.map(res => res.json())
.subscribe(data => {
this.token_acces = data;
observer.next(data);
},(err) => {
console.log("Error occurred: ", err);
observer.error(err);
});
});
}
在HomePage类或任何其他调用类/代码方法中:
In HomePage class or any other calling class/method of code:
login(): void{
this.myClassService.login(this.id, this.pwd).subscribe((data) => {
this.navCtrl.push(SearchPage, { token : this.myClassService.getToken()});
},
(err) => {
console.log("Error occurred : ", err);
});
}
您甚至不需要使用 getToken()
。您可以在 subscribe()
中使用数据
,这将为您提供有关令牌的必要数据。
You do not even need to use getToken()
. You can just use data
in subscribe()
which will give you necessary data about token.
这篇关于Ionic2:处理提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!