【问题标题】:NullInjectorError: No provider for String! in angular 6NullInjectorError:没有字符串的提供者!在角度 6
【发布时间】:2019-02-02 14:49:09
【问题描述】:

父类

import { BadRequestError } from './../common/bad-request-error';
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
import { Http } from '@angular/http';
import { Injectable, OnInit } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { throwError} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private url: string , private http: Http) {
 }

getAll() {
 return this.http.get(this.url).pipe(catchError(this.handleError));
}

delete(id) {
  return this.http.delete(this.url + '/' + id)
   .pipe(
    catchError(this.handleError));
 }

update(resource) {
  return this.http.patch(this.url + '/' + resource.id, 
    JSON.stringify({isRead: true})).pipe(
      catchError(this.handleError));
  }

create(resource) {
 return this.http.post(this.url , JSON.stringify(resource))
   .pipe(
     catchError(this.handleError)
   );

}

 private handleError(err: Response) {
   if (err.status === 404) {
     return throwError(new NotFoundError());
 } if (err.status === 400) {
   return throwError(new BadRequestError(err.json()));
 }
   return throwError(new AppError(err));
 }
}

子类

 import { DataService } from './data.service';
 import { Http } from '@angular/http';
 import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root'
})
export class PostService extends DataService {
  constructor(http: Http) {
    super('https://jsonplaceholder.typicode.com/posts' , http);
 }

}

从子类传递字符串时出现以下错误。

错误:StaticInjectorError(AppModule)[String]:
StaticInjectorError(平台:核心)[字符串]: NullInjectorError:没有字符串的提供者! 在 NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:1062) 在 resolveToken (core.js:1300) 在 tryResolveToken (core.js:1244) 在 StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1141) 在 resolveToken (core.js:1300) 在 tryResolveToken (core.js:1244) 在 StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1141) 在 resolveNgModuleDep (core.js:8376) 在 NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:9064) 在注入 (core.js:1403)

请建议如何解决上述错误。

【问题讨论】:

  • 你应该在构造函数之外声明这个字符串。 Ref below link

标签: angular dependency-injection


【解决方案1】:

添加到服务角度的任何参数都将尝试由 DI 系统注入。 DataService 在这种情况下考虑了 api 服务的基类,我们不需要将其设为 injectable。所以只需删除可注入装饰器

数据服务

export class DataService {

  constructor(private url: string , private http: Http) {
 }
 ...    

}

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2020-05-03
    • 1970-01-01
    • 2019-11-16
    • 2021-01-20
    相关资源
    最近更新 更多