除去离子4存储

问题描述 投票:0回答:1

我在Ionic应用程序中存储了凭证令牌,要执行注销操作,我需要删除其中存储的令牌。这是我的LoginService:

// imports skipped;

export class LoginService implements CanActivate {
    private authToken: string;
    private httpService: string;

    constructor(
        private handler: HttpBackend,
        private router: Router,
        private storage: Storage
    ) {
        this.httpService = new HttpClient(handler);
    }

    private generateToken(login: string, password: string) {
        return btoa(`${login}:${password}`);
    }

    authenticate(login: string, password: string, webserviceURL: string) {
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                Authorization: `Basic ${this.generateToken(login, password)}`
            })
        };
        return this.httpClient.get(`http://${webserviceURL}/api/version/`, httpOptions);
    }

    async saveToken(login: string, password: string) {
        this.authToken = this.generateToken(login, password);
        return await this.storage.set('AUTH_TOKEN', this.authToken);
    }

    async getToken() {
        return await this.storage.get('AUTH_TOKEN');
    }

    async clearData() {
        this.authToken = null;
        return await this.storage.remove('AUTH_TOKEN');
    }

    canActivate() {
        if (this.authToken) {
            return true;
        }
        this.router.navigateByUrl('login');
    }
}

并且在对该服务的测试中,我得到了以下内容:

        const expectedToken = btoa('testLogin:testPassword');

        service.saveToken('testLogin', 'testPassword').then(() => {
            service.getToken().then(savedToken => {
                expect(savedToken).toEqual(expectedToken);
            });
        });

        service.clearData().then(() => {
            service.getToken().then(savedToken => {
                expect(savedToken).toBe(null);
            });
        });

因此,无论何时我运行测试,最后一个测试用例都会失败,因为出于某种原因令牌不会从存储中删除。这是测试输出:Error: Expected 'dGVzdExvZ2luOnRlc3RQYXNzd29yZA==' to be null。如何正确从存储中删除价值?

asynchronous ionic-framework async-await ionic4 ionic-storage
1个回答
0
投票

第二次尝试...如果您的代码在一种方法中运行,那么它必须全部嵌套,否则它将只在另一个方法中运行?

    const expectedToken = btoa('testLogin:testPassword');

    service.saveToken('testLogin', 'testPassword').then(() => {
        service.getToken().then(savedToken => {
            expect(savedToken).toEqual(expectedToken);

            service.clearData().then(() => {
                service.getToken().then(savedToken => {
                    expect(savedToken).toBe(null);
                });
            });
        });
    });
© www.soinside.com 2019 - 2024. All rights reserved.