kittencup / angular2-ama-cn

angular2 随便问
692 stars 101 forks source link

在ng2中定义一个全局变量 #202

Closed tanyun1111 closed 8 years ago

tanyun1111 commented 8 years ago

我在登录成功后,需要保留一个token值,每次请求服务都需要带上这个token值,这样要怎么实现?

caoren commented 8 years ago

不需要定义全局变量 你可以存储在一个对象中,然后export出来,你要用这个对象的地方再import过来就可以;

var obj = {
    token : '',
    set(val){
        this.token = val;
    }
}
export {obj}
hstarorg commented 8 years ago

一般做成一个Context服务

tanyun1111 commented 8 years ago

能给段代码吗

hstarorg commented 8 years ago

class Context{ constrctor(){ this.token = 'xxx'; } }

holdlg commented 6 years ago

@caoren @tanyun1111

var obj = {
    token : '',
    set(val){
        this.token = val;
    }
}
export {obj}

页面刷新, 值就没有了。。。。。