【问题标题】:Using Storage with Ionic 2将存储与 Ionic 2 一起使用
【发布时间】:2017-01-25 20:33:12
【问题描述】:

我正在尝试使用 Ionic 2 中的存储,如文档所示:

ionic storage ducumentation

    import {Http} from '@angular/http';
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Component} from '@angular/core';
import {Storage} from '@ionic/storage';
import 'rxjs/add/operator/map';
// import {GlobalVars, getMyGlobalVar} from './global-vars';



export class User {
  token: string;

  constructor(token: string) {
    this.token = token
  }
}

@Injectable()
export class AuthService {

    static get parameters() {
        return [[Http]];
    }

    constructor(public http: Http, storage:Storage) {
        this.http = http;
      this.storage = storage;
    }

  currentUser: User;
  public login(credentials) {
    // console.log(getMyGlobalVar())
    if (credentials.username === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      return Observable.create(observer => {
        // At this point make a request to your backend to make a real check!
        // send username and password to server
        // save user auth token


                    var creds = {username:credentials.username, password:credentials.password}
                    this.http.post('http://someurl.com/api-token-auth/', creds).subscribe(data => {
            this.storage.set('1984_token', data.json().token);
                        let access = (true);
                        this.currentUser = new User(data.json().token);
                        observer.next(access);
                        observer.complete();

                    }, error => {
                let access = (false);
                        observer.next(access);
            }, () => {

                    });
      });
    }
  }


  public getUserInfo() : User {
    return this.currentUser;
  }

  public logout() {
    return Observable.create(observer => {
      this.currentUser = null;
      observer.next(true);
      observer.complete();
    });
  }
}

它说它不能设置未定义的属性,所以存储是未定义的。 Stprage 也被导入 app.module 并作为提供者添加。我打算将其存储在提供程序中。

Runtime Error
Cannot read property 'set' of undefined
Stack
TypeError: Cannot read property 'set' of undefined
    at SafeSubscriber._this.http.post.subscribe.access [as _next] (http://localhost:8100/build/main.js:37296:34)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/main.js:44390:16)
    at SafeSubscriber.next (http://localhost:8100/build/main.js:44339:22)
    at Subscriber._next (http://localhost:8100/build/main.js:44292:26)
    at Subscriber.next (http://localhost:8100/build/main.js:44256:18)
    at XMLHttpRequest.onLoad (http://localhost:8100/build/main.js:54386:38)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9723)
    at Object.onInvokeTask (http://localhost:8100/build/main.js:34819:37)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9659)
    at e.runTask (http://localhost:8100/build/polyfills.js:3:7083)
Ionic Framework: 2.0.0-rc.5
Ionic Native: 2.2.11
Ionic App Scripts: 1.0.0
Angular Core: 2.2.1
Angular Compiler CLI: 2.2.1
Node: 4.4.4
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36

我找不到任何明确的文档如何使用它

package.json:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "2.2.1",
    "@angular/compiler": "2.2.1",
    "@angular/compiler-cli": "2.2.1",
    "@angular/core": "2.2.1",
    "@angular/forms": "2.2.1",
    "@angular/http": "2.2.1",
    "@angular/platform-browser": "2.2.1",
    "@angular/platform-browser-dynamic": "2.2.1",
    "@angular/platform-server": "2.2.1",
    "@ionic/storage": "^1.1.7",
    "ionic-angular": "2.0.0-rc.5",
    "ionic-native": "2.2.11",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.6.26"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.0.0",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [
    "ios",
    {
      "platform": "ios",
      "version": "",
      "locator": "ios"
    }
  ],
  "description": "isango_mobile: An Ionic project"
}

【问题讨论】:

  • 只需在构造函数中删除this.storage = storage;
  • @AmruthLS 取决于 Harry 使用的版本,但该文档已过时。我假设 Harry 使用的是 RC.0 以上的版本,否则他会/应​​该提到它。
  • 我刚刚安装了它,所以它是最新的。
  • 请看更新后的实际代码
  • 我会将您的订阅响应更改为 Http 响应类型。 .subscribe(data: Response) 并从 '@angular/http' 导入响应

标签: local-storage ionic2


【解决方案1】:

在 typescript 中,您需要使用 this 来访问类变量。

export class MyApp {
  constructor(public storage: Storage) {
    //this.storage = storage; this line is not required as you have set access specifier in constructor parameter.
  }
  foo () {
     this.storage.set('name', 'Max');
  } 

【讨论】:

  • 我的代码中有这样的内容,这是问题中的错字。但这不是问题
  • 你在使用 sqlite 插件吗?您是在浏览器还是设备中尝试?
  • 是的,我在浏览器中。代码在提供程序中。
  • 我添加了 package.json 内容
  • 你使用的是静态获取参数?
【解决方案2】:

好的,我就是这样使用并为我工作。

import { Storage } from '@ionic/storage';

 constructor(
 private storage : Storage){}

 foo(){
    this.storage.set('name','Max');
 }

并且app.module不需要任何更改

【讨论】:

  • 同样的错误:error_handler.js:47 例外:无法读取未定义的属性“设置”
【解决方案3】:

我遇到了同样的问题,在页面中对我来说很好,并将我的测试令牌集记录在另一个页面中,例如

    import { Storage } from '@ionic/storage'
    ....

    export class AccountPage {

      settings: AppSettings;
      loading: any;

      constructor(public http: Http, public navCtrl: NavController, public storage: Storage, private platform: Platform, private loadingCtrl: LoadingController, public authService: AuthService) {

      }

     ionViewDidLoad() {
    this.storage.get('token').then((token) => {
          console.log('token ' + token);
        });
        }

但我发现它在提供程序中未定义。在构造函数中使用“公共存储:存储”来注入存储,然后使用 this.storage 获取/设置。

对于页面和提供程序,我以相同的方式处理存储,但使用提供程序并不快乐。在 app.module.ts 中添加存储:

@NgModule({
  declarations: [
    RVCommunityApp,
    AccountPage,
    DirectoryPage,
    FaqPage,
    ModalPage,
    OffersPage,
    OfferDetailsPage,
    QRCodePage,
    TabsPage,
    TouchpointsPage,
    TouchpointDetailsPage,
    VendorPage
  ],
  imports: [
    IonicModule.forRoot(RVCommunityApp, {
      tabsPlacement: 'bottom',
      statusbarPadding: true,
      tabSubPages: true,
      platforms: {
        ios: {
          statusbarPadding: true
        }
      }
    }, {}),
    CloudModule.forRoot(cloudSettings)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    RVCommunityApp,
    AccountPage,
    DirectoryPage,
    FaqPage,
    ModalPage,
    OffersPage,
    OfferDetailsPage,
    QRCodePage,
    TabsPage,
    TouchpointsPage,
    TouchpointDetailsPage,
    VendorPage
  ],
  providers: [AuthService, CategoryService, ConnectivityService, ContentService, DirectoryService, ModalService, OffersService, TouchpointService, AppSettings, Storage]
})
export class AppModule {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2017-03-09
    • 2018-12-06
    • 1970-01-01
    • 2011-08-25
    • 2018-05-23
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多