这就是在Ionic + Angular项目中,当我在Chrome浏览器中对其进行测试时出现的错误。
到目前为止,我遵循的步骤:
ionic start testApp (with angular and blank choices)
ng build
ionic capacitor add android
ionic serve
一切正常,直到这里。现在,如果我尝试存储并从存储中检索一些信息:
home.page.ts
import { Component, OnInit } from '@angular/core';
import { HomeService } from './home.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{
constructor(private homeService: HomeService) {}
ngOnInit() {
debugger;
this.homeService.setStoredUser().then( storedData => {
debugger;
console.log('Stored: '+storedData);
this.homeService.getStoredUser().then( storedData => {
debugger;
console.log('Retrieved: '+storedData);
});
});
}
}
home.service.ts(添加到提供的数组中的app.module.ts中)
import { Injectable } from '@angular/core';
import { Plugins } from '@capacitor/core';
import { Platform } from '@ionic/angular';
@Injectable()
export class HomeService {
constructor(private platform: Platform) {}
getStoredUser() {
let p = null;
try {
debugger;
console.log(this.platform);
p = Plugins.Storage.get({key: 'authData'});
console.log(p);
} catch (error) {
debugger;
console.log(error);
}
return p;
}
setStoredUser() {
let p = null;
try {
debugger;
console.log(this.platform);
p = Plugins.storage.set({key: 'authData', value: 'Hello!'});
console.log(p);
} catch (error) {
debugger;
console.log(error);
}
return p;
}
}
这是开发人员控制台中的错误:
> ZoneAwarePromise {__zone_symbol__state: 0, __zone_symbol__value:
> "storage does not have web implementation."}__zone_symbol__state:
> false__zone_symbol__value: "storage does not have web
> implementation."Symbol(Symbol.toStringTag): (...)__proto__: Object
> core.js:9110 ERROR Error: Uncaught (in promise): storage does not have
> web implementation.
> at resolvePromise (zone-evergreen.js:797)
> at resolvePromise (zone-evergreen.js:754)
> at zone-evergreen.js:858
> at ZoneDelegate.invokeTask (zone-evergreen.js:391)
> at Object.onInvokeTask (core.js:34182)
> at ZoneDelegate.invokeTask (zone-evergreen.js:390)
> at Zone.runTask (zone-evergreen.js:168)
> at drainMicroTaskQueue (zone-evergreen.js:559)
关于我在做什么错或错过的任何想法?
[如果有人遇到相同的问题。找到了具有最新版本的Angular和Ionic的存储插件的工作版本。
与之前相同的示例,但是更改了该另一类的服务,并相应地更改了组件:
import { Plugins } from '@capacitor/core';
const { Storage } = Plugins;
export async function set(key: string, value: any): Promise<void> {
await Storage.set({
key: key,
value: JSON.stringify(value)
});
}
export async function get(key: string): Promise<any> {
const item = await Storage.get({ key: key });
return JSON.parse(item.value);
}
export async function remove(key: string): Promise<void> {
await Storage.remove({
key: key
});
}
我不知道为什么这对我有用,而第一个示例不起作用。