DI的新方法(角度为6+)出现“ NullInjectorError:StaticInjectorError(AppModule)”错误

时间:2019-11-23 14:21:52

标签: angular ionic-framework

我正在使用Angular 8,在这里找不到任何对我有帮助的问题。遵循本教程:https://ionicframework.com/docs/intro/first-app,我创建了一个PhotoService:

import { Injectable } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';

@Injectable({
  providedIn: 'root'
})

class Photo {
  data: any;
}

export class PhotoService {

  public photos: Photo[] = [];

  constructor(private camera: Camera) { }

  takePicture() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    };

    this.camera.getPicture(options).then((imageData) => {
      // Add new photo to gallery
      this.photos.unshift({
          data: 'data:image/jpeg;base64,' + imageData
      }); }, (err) => {
      // Handle error
      console.log("Camera issue: " + err);
  });

  }

}

然后将其注入相关组件:

import { Component } from '@angular/core';
import { PhotoService } from '../services/photo.service';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
})
export class Tab2Page {

  constructor(public photoService: PhotoService) {}

}

但这产生了一个错误:

consolelogs.js:49 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Tab2Page -> PhotoService]: 
  StaticInjectorError(Platform: core)[Tab2Page -> PhotoService]: 
    NullInjectorError: No provider for PhotoService!
NullInjectorError: StaticInjectorError(AppModule)[Tab2Page -> PhotoService]: 
  StaticInjectorError(Platform: core)[Tab2Page -> PhotoService]: 
    NullInjectorError: No provider for PhotoService!

但是当我以这种旧方式注入服务时:

import { Component } from '@angular/core';
import { PhotoService } from '../services/photo.service';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
  providers: [PhotoService]
})
export class Tab2Page {

  constructor(public photoService: PhotoService) {}

}

一切正常。.为什么新的注射方式不起作用? 谢谢。

0 个答案:

没有答案