![](/img/trans.png)
[英]Argument of type null is not assignable to parameter of type RadioGroupState
[英]Argument of type 'null' is not assignable to parameter of type 'HttpClient' on angular 11
我刚刚学习成为开发人员,在传递参数 null 时遇到问题,如下所示:
todos.component.spec.ts
import { TodosComponent } from './todos.component';
import { TodoService } from './todo.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
describe('TodosComponent', () => {
let component: TodosComponent;
let service: TodoService;
beforeEach(() => {
service = new TodoService(null); //Argument of type 'null' is not assignable to parameter of type
'HttpClient'.ts(2345)
component = new TodosComponent(service);
});
it('6.1 Should set todos property with the items returned from the server', () => {
const todos = [1, 2, 3];
spyOn(service, 'getTodos').and.callFake(() => {
return Observable.from([todos]);
});
component.ngOnInit();
expect(component.todos).toBe(todos);
});
});
todo.component.ts
import { TodoService } from './todo.service'
export class TodosComponent {
todos: any;
message: any;
constructor(private service: TodoService) {}
ngOnInit() {
this.service.getTodos()
.subscribe(t => this.todos = t);
}
add() {
var newTodo = { title: '... ' };
this.service.add(newTodo)
.subscribe(
( t => this.todos.push(t) ),
( err => this.message = err) );
}
delete(id: number) {
if (confirm('Are you sure?'))
this.service.delete(id)
.subscribe();
}
}
todo.services.ts
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
export class TodoService {
constructor(private http: HttpClient) {
}
add(todo: { title: string; }) {
return this.http.post('...', todo)
.map((r => r.json()));
}
getTodos() {
return this.http.get('...')
.map((r => r.json()));
}
delete(id: number) {
return this.http.delete('...')
.map((r => r.json()));
}
}
这里我使用的环境。
Angular CLI: 11.2.6
Node: 12.16.2
OS: win32 x64
Angular: 11.2.7
... animations, common, compiler, compiler-cli, core, elements
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1102.6
@angular-devkit/build-angular 0.1102.6
@angular-devkit/core 11.2.6
@angular-devkit/schematics 11.2.6
@angular/cdk 11.2.6
@angular/cli 11.2.6
@schematics/angular 11.2.6
@schematics/update 0.1102.6
ng-packagr 11.2.4
rxjs 6.6.6
typescript 4.0.7
您需要将HttpClient
注入到TodoService
,因为它将它作为参数。 由于我们不想发出物理 http 请求(因为我们只测试代码而不是 api),我们将对HttpClient
进行间谍活动,并将其传递给服务。
import { of } from 'rxjs'
describe('TodosComponent', () => {
beforeEach(() => {
const spy = jasmine.createSpyObj('HttpClient', { post: of({}), get: of({}) })
service = new TodoService(spy)
})
})
边注:
您可以通过执行以下操作来简化您的间谍:
let todos = [1,2,3,4]
spyOn(service, 'getTodos').and.returnValue(of(todos));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.