【问题标题】:angular2: strange null error from an injected serviceangular2:来自注入服务的奇怪空错误
【发布时间】:2016-12-19 19:19:38
【问题描述】:

我有一个非常基本的网络应用程序,它有一个Home component,它使用localStorage 服务来检查是否已设置本地 IP。如果尚未设置本地 IP,则必须导航到可以输入本地 IP 的设置页面。当我运行我的应用程序(使用 ng-cli)时,出现以下错误。似乎即使我在constructor 中注入了localStorageService,但由于某种原因它是null……知道可能出了什么问题吗?

我的error:

main.bundle.js:42342
EXCEPTION: Uncaught (in promise): Error: Error in ./HomeComponent class HomeComponent_Host - inline template:0:0 caused by: Cannot read property 'localIP'
of null
TypeError: Cannot read property 'localIP' of null
    at LocalStorageService.getLocalIP (
http://localhost:4200/main.bundle.js:64378:18)
    at HomeComponent.ngOnInit (
http://localhost:4200/main.bundle.js:64008:46)
    at Wrapper_HomeComponent.detectChangesInInputProps (/AppModule/HomeComponent/wrapper.ngfactory.js:18:53)
    at _View_HomeComponent_Host0.detectChangesInternal (/AppModule/HomeComponent/host.ngfactory.js:30:27)
    at _View_HomeComponent_Host0.AppView.detectChanges (
http://localhost:4200/main.bundle.js:59869:14)
    at _View_HomeComponent_Host0.DebugAppView.detectChanges (
http://localhost:4200/main.bundle.js:59974:44)
    at ViewRef_.detectChanges (
http://localhost:4200/main.bundle.js:43438:20)
    at RouterOutlet.activate (
http://localhost:4200/main.bundle.js:46946:42)
    at ActivateRoutes.placeComponentIntoOutlet (
http://localhost:4200/main.bundle.js:15157:16)
    at ActivateRoutes.activateRoutes (
http://localhost:4200/main.bundle.js:15135:22)

我的HomeComponent:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RestService } from '../../services/rest.service';
import { LocalStorageService } from '../../services/local-storage.service';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private restService: RestService, private localStorageService: LocalStorageService, private router: Router) {
this.localStorageService = new LocalStorageService();     
}

  ngOnInit() {    
      let ip = this.localStorageService.getLocalIP();
      if (!ip.length > 0) {
          this.router.navigate(['settings']);
      }
      console.log(this.localStorageService.getLocalIP());  


  }

}

我的LocalStorageService:

import { Injectable } from '@angular/core';

@Injectable()
export class LocalStorageService {

saveLocalIP(ip: string): void {
    let localData = localStorage.getItem('retail_mobile');
    if (localData) {
        localData = JSON.parse(localData);
    } else {
        localData = "";
    }

    localData = "{localIP:" + ip + "}";
    localStorage.setItem('retail_mobile', JSON.stringify(localData));   
}

getLocalIP() {
    let data = JSON.parse(localStorage.getItem('retail_mobile'));
    if (!data.localIP) {        
        console.log("No local IP found in local storage...");
        return '';
    }

    return data.localIP;
}

  constructor() { }

}

【问题讨论】:

  • 删除this.localStorageService = new LocalStorageService();

标签: angular local-storage


【解决方案1】:

我认为问题出在 getLocalIP() 函数中。

getLocalIP() {
    let data = JSON.parse(localStorage.getItem('retail_mobile'));
    ................
    ................
}

你得到的数据是 null。因此,再多做一次检查并针对 null 验证数据。

if (data && !data.localIP)

【讨论】:

  • 感谢@Ankush Jain 也没有摆脱错误...似乎 localService 实例由于某种原因为空...
  • 谢谢。当我在 getLocalIP 函数中添加对 null 的检查时,它起作用/消除了错误...
【解决方案2】:

我猜你打算只使用

localData = {localIP: ip };

saveLocalIP

【讨论】:

    【解决方案3】:

    无需创建新的服务实例 remove this.localStorageService = new LocalStorageService();

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { RestService } from '../../services/rest.service';
    import { LocalStorageService } from '../../services/local-storage.service';
    
    @Component({
      selector: 'home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
    
      constructor(private restService: RestService, private localStorageService: LocalStorageService, private router: Router) {
    
    }
    
      ngOnInit() {    
          let ip = this.localStorageService.getLocalIP();
          if (!ip.length > 0) {
              this.router.navigate(['settings']);
          }
          console.log(this.localStorageService.getLocalIP());  
    
    
      }
    
    }
    

    【讨论】:

    • 我补充说,只是为了确保 localService 不能为空......删除它似乎并没有改变任何东西,仍然得到同样的错误。
    • 你在module.ts中添加了LocalStorageService
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多