簡體   English   中英

噴油嘴無法在Angular2 / Ionic2中正常工作

[英]Injector not working as expected in Angular2/Ionic2

我已經定義了如下服務:

//storageService.ts
import { Injectable } from '@angular/core';
import {Storage, SqlStorage} from 'ionic-angular';

@Injectable()
export class StorageService {
    storage: any;

    constructor() {
        this.storage = new Storage(SqlStorage);
    }

    getUser() {
        return this.storage.get('user');
    }

}

我將其注入另一個類,如下所示:

Profile.ts
import {StorageService} from '../../services/storageService';

@Page({
    templateUrl: 'build/pages/profile/profile.html',
    providers: [StorageService]
})
export class ProfilePage {


    constructor(private http: Http, storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });

    }

}

但是我一直收到錯誤:

Cannot read property 'getUser' of undefined

由於我將服務注入到構造函數中,所以我收到此錯誤?

因為您正在使用TypeScript,所以需要在構造函數中將提供程序定義為privatepublic ,這將在頁面類中自動創建提供程序的實例,例如:

constructor(private http: Http, private storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });    
    }

對您問題的其他答復提供了JavaScript解決方案,該解決方案對您不起作用。

據我所知,您需要在Ionic中使用靜態parameters ,例如:

@Page({
    templateUrl: 'build/pages/profile/profile.html',
    providers: [StorageService]
})
export class ProfilePage {

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

    constructor(private http: Http, storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });
    }
}

顯然我沒有正確使用打字稿。

必須聲明如下的storageService:

constructor(private http: Http,private storageService: StorageService)  {

即我錯過了私人關鍵字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM