我正在尝试通过 Angular 在 Web 和移动设备之间使用 Nativescript 代码共享 我安装了最新的稳定版本等。 但是很多 npm 模块,例如:“nativescript-localstorage”,当我开始使用它时,它给了我: “无法解析‘tns-core-modules/file-system/file-system-access’” 即使模块作者在更新他的模块等几个小时后对其进行了测试。 但对我来说它不起作用
最佳答案
我遇到了同样的问题。所以我做了一个服务,它是本地 localStorage 的包装器。
之后,我将包装器注入(inject)到我的网络应用程序模块和移动应用程序模块中。但是对于移动应用程序模块,我注入(inject)了 nativescript-localstorage 而不是我的包装器。
就像我的包装器具有与 nativescript-localstorage 类相同的功能一样,Angular 只看到火,我可以使用我的包装器来处理移动和网络中的 localStorage!
实际上,当它在网络上下文中时,Angular 使用“本地”localStorage,而当它在移动上下文中时,Angular 使用 nativescript-localstorage 库。
在我的代码下面。
我的服务包装器:
import { Injectable } from "@angular/core";
@Injectable()
export class CustomStorageService {
setItem(key, value){
localStorage.setItem(key, value);
}
getItem(key){
return localStorage.getItem(key);
}
removeItem(key){
localStorage.removeItem(key);
}
clear(){
localStorage.clear();
}
}
在app.module.ts中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { CustomStorageService } from './commons/core/services/guard/custom-storage.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [
CustomStorageService
],
bootstrap: [AppComponent]
})
export class AppModule { }
我的app.module.tns.ts:
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptModule } from 'nativescript-angular/nativescript.module';
import { NativeScriptHttpClientModule } from 'nativescript-angular/http-client';
import * as mobileStorage from 'nativescript-localstorage';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule,
NativeScriptFormsModule
],
providers: [
{
provide: CustomStorageService,
useValue: mobileStorage
}
],
bootstrap: [AppComponent],
schemas: [NO_ERRORS_SCHEMA]
})
export class AppModule { }
包装器的用法示例:
import { Injectable } from '@angular/core';
import { CustomStorageService } from './custom-storage.service';
@Injectable()
export class TokenService {
constructor(private storage: CustomStorageService){
}
getToken(): String {
return this.storage.getItem('token');
}
saveToken(token: String) {
this.storage.setItem('token',token);
}
destroyToken() {
this.storage.removeItem('token');
}
destroyAll(){
this.storage.removeItem('token');
this.storage.removeItem('user_id');
this.storage.removeItem('user_name');
this.storage.removeItem('full_name');
}
destroyUser() {
this.storage.removeItem( 'currentUser' );
}
cleanLocalStorage() {
this.storage.clear();
}
}
希望对您有所帮助。
关于angular - 无法在代码共享项目中使用 Nativescript Localstorage 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52313308/