在处理我遇到问题的程序时,构造函数及其子类的依赖注入(inject)。
constructor(private url: string, private http: Http) { }
constructor(http: Http) {
super('https://jsonplaceholder.typicode.com/posts', http);
}
在此重构之前(移动所有常见的 CRUD 操作并通过子类对其进行扩展),我的代码按预期工作,但 之后 以上更改我收到以下错误:Date: 2020-03-22T15:26:23.248Z - Hash: 7130497a38c152c58258
5 unchanged chunks
Time: 1859ms
ERROR in src/app/services/data.service.ts:14:23 - error NG2003: No suitable injection token for parameter 'url' of class 'DataService'.
Found string
14 constructor(private url: string, private http: Http) { }
此外,当我从 Datsource 构造函数中删除 url 参数(相应地修改 PostService.ts)时,api 正在按预期工作。不知道为什么!!!我在用:
Angular CLI:9.0.4
节点:12.16.1
操作系统:win32 x64
Angular :
...
Ivy 工作区:
包版本
@angular-devkit/架构师 0.900.4
@angular-devkit/核心 9.0.4
@angular-devkit/schematics 9.0.4
@原理图/Angular 9.0.4
@原理图/更新 0.900.4
rxjs 6.5.3
数据服务.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AppError } from '../common/app-error';
import { NotFoundError } from '../common/not-found-error';
import { BadInput } from '../common/bad-input';
@Injectable()
export class DataService {
// private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private url: string, private http: Http) { }
getAll() {
return this.http.get(this.url).pipe(catchError(this.errorHandle));
}
create(resource) {
return this.http.post(this.url, JSON.stringify(resource))
.pipe(catchError(this.errorHandle));
}
update(resource) {
return this.http.patch(this.url + '/' + resource.id, JSON.stringify({ isRead: true }))
.pipe(catchError(this.errorHandle));
}
delete(resource) {
return this.http.delete(this.url + '/' + resource.id)
.pipe(catchError(this.errorHandle));
}
private errorHandle(error: Response){
if (error.status === 404) {
return throwError(new NotFoundError());
}
if (error.status === 400) {
return throwError(new BadInput(error.json()));
}
return throwError(new AppError(error));
}
}
PostService.ts import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { DataService } from './data.service';
@Injectable()
export class PostService extends DataService {
constructor(http: Http) {
super('https://jsonplaceholder.typicode.com/posts', http);
}
}
最佳答案
在 数据服务.ts :
更新构造函数。
//import { Inject } from '@angular/core';
constructor(@Inject(String) private url: string, private http: Http)
更新(解释):根据https://angular-2-training-book.rangle.io/di/angular2/inject_and_injectable ;
@Inject()
是一种手动机制,用于让 Angular 知道必须注入(inject)参数。@Inject
装饰器仅用于注入(inject)原语。原始类型 是数字、字符串、 bool 值、大整数、符号、空值、未定义。
可以使用的另一种( 替代 )方式是:
//import { Inject } from '@angular/core';
@Inject('url') private url: string;
关于Angular 9 : Error NG2003: No suitable injection token for parameter 'url' of class 'DataService' . 找到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60801513/