简体   繁体   English

全局变量以及如何在IONIC3中传递值

[英]Global Variable and how pass the value in IONIC3

I think my problem is very simple, but i'm certainly sothing passing me. 我认为我的问题很简单,但我的确可以接受。

I need to put a TOKEN for the HTTP resquests in a global variable after login. 登录后,我需要将HTTP请求的令牌放在全局变量中。 In my Login page, the HTTP get, return an object with: HTTP code (200,403,403), a Message("Success") and the TOKEN, and i pass this object to the HOME.ts page true the NavController. 在我的登录页面中,HTTP get返回一个带有以下内容的对象:HTTP代码(200,403,403),一个Message(“ Success”)和TOKEN,然后将该对象传递给HOME.ts页面,即NavController。

this.navCtrl.setRoot(HomePage,{
    data   <<--- Object                        
  });

But when i try to put this return "data" in a object of the type "Login" 但是,当我尝试将此返回“数据”放入“登录”类型的对象中时

export class Login {

code:number;
token:string;
message:string;

constructor(code?:number, token?:string, message?:string){
    this.code = code;
    this.token = token;
    this.message = message;

}

} }

To put the atribute Login.token inside the global variable, nothing happen. 要将属性Login.token放在全局变量内,则什么也没有发生。

I made some test and this is what i have until know. 我做了一些测试,这就是我所知道的。

In the HOME.ts i put some console.log, to figure it out what happen. 在HOME.ts中,我放置了一些console.log,以了解发生了什么。

 console.log(this.navParams.data.data); ----> RESULT 1

console.log(this.navParams.get("data"));    ----> RESULT 2

this.dadosRest = this.navParams.get("data");

console.log(this.dadosRest);  ----> RESULT 3

console.log(this.dadosRest.token); -----> RESULT 4

RESULT 1 and 2 and 3: 结果1、2和3:

{success: {…}}

success : code : 200 message : "Welcome admin - This is your token (generated by a previous call)" token : "676f71bab54dad7589c3d1b6b5f5b24de0f8c484" proto : Object proto : Object 成功:代码:200消息:“欢迎管理员-这是您的令牌(由上一个调用生成)”令牌:“ 676f71bab54dad7589c3d1b6b5f5b24de0f8c484” 原型 :对象原型 :对象

RESULT 3 : 结果3:

undefined 未定义

Why i can't put this return inside the object Login to manage? 为什么我不能将此返回值放到Login对象中进行管理?

Do not use globals. 不要使用全局变量。 You can use either a shared service (create a service that you inject in the components, and them you use a method to store there your token and another one to read the stored value) or store it in some kind of storage (like the Ionic Storage ) or even (and more complicated) use some state container, like Redux. 您既可以使用共享服务 (创建要在组件中注入的服务,又可以使用一种方法在其中存储令牌并使用另一种方法来读取存储的值)或将其存储在某种类型的存储中(例如Ionic) Storage )甚至(更复杂)使用某些状态容器,例如Redux。

Anyway: don't pollute the global scope. 无论如何:不要污染全球范围。 Maybe you could do this using something like 也许您可以使用类似的方法

window.token = 'the token'

but this is not a good ideia. 但这不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM