无法使用 localStorage 或 sessionStorage 从内部订阅同步到外部订阅 [英] Cannot get synchronization from inside subscribe to outside subscribe using localStorage or sessionStorage

查看:15
本文介绍了无法使用 localStorage 或 sessionStorage 从内部订阅同步到外部订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个映射:

User     *----------------------------1     Role

从用户列表中,我去咨询此列表中的一位用户.要获取有关所选用户的一些信息,我需要使用 localSorageinside subscribeoutside subscribe 获取一个对象.

From the list of users, I go to consult one user from this list. To get some informations about that selected user, I need to use localSorage to get an object from inside subscribe to outside subscribe.

下面是方法:

this.userService.getAllRolesOfActualUser(user.id).subscribe(listRoles =>
{

     let roles:Array<Role> = [];

     if (listRoles)
     {
         listRoles.forEach((role) =>
         {
             roles.push(new Role(role.id, role.name, role.selected));
         });
     }

     sessionStorage.removeItem("roles");
     sessionStorage.setItem("roles", JSON.stringify(roles));
     console.log("1. Inside Subscribe- " + user.id + "--------------: " + 
     sessionStorage.getItem("roles"));

});

console.log("2. Outside Subscribe- " + user.id + "--------------: " + sessionStorage.getItem("roles"));

user.service.ts 上,我有:

getAllRolesOfActualUser(id: number): Observable<any>
    {
        return this.http.get(`${this.baseUrl}/users/roles/${id}`);
    }

我的问题是,通常我得到的是前一个咨询用户的值,而不是这个 截图:

My problem is that usually I got the value of the previous consulted user not the actual user a described by this screenshot:

你能帮我解决这个问题吗?!.非常感谢.

Could you please help me solving that issue ?!. Big thanks.

推荐答案

你必须使用promise:

    ses : String[];
    expertises : String[] = [];

    async getUri(userId: number)
        {
            let affected = this.userService.getExpertisesListByIdUserPromise(userId);

            await affected.then((uri) =>
            {
                this.ses = uri;
            })

            return this.ses;
        }

在 ngOnInit 上,我有

and on ngOnInit, I have

this.getUri(16).then(item => 
        {
            item.forEach(pro=>
            {
                this.expertises.push(pro);
            });
        });

在服务文件中,您有:

getExpertisesListByIdUserPromise(id: number): Promise<any>
    {
        return this.http.get(`${this.baseUrl}/users/expertises/${id}`).toPromise();
    }

HTH

这篇关于无法使用 localStorage 或 sessionStorage 从内部订阅同步到外部订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆