我想恢复API数据,但这给了我错误。
无法解析PostsComponent的所有参数
posts.component.ts
import { HttpClient } from 'selenium-webdriver/http';
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/Http';
@Component({
selector: 'posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
constructor(private http : Http) {
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(response=>
{ console.log(response)
})
}
ngOnInit() {
}
}
app.module.ts
import { HttpModule } from '@angular/Http';
import { EmailService } from './email.service';
import { CoursesService } from './courses.service';
import { CoursesComponent } from './courses.component';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms'
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CourseComponent } from './course/course.component';
import { ResumePipe } from './resume.pipe';
import { FavoriteComponent } from './favorite/favorite.component';
import { PanelComponent } from './panel/panel.component';
import { InputFormatDirective } from './input-format.directive';
import { ContactFormComponent } from './contact-form/contact-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { PostsComponent } from './posts/posts.component';
@NgModule({
declarations: [
AppComponent,
CourseComponent,
CoursesComponent,
ResumePipe,
FavoriteComponent,
PanelComponent,
InputFormatDirective,
ContactFormComponent,
SignupFormComponent,
PostsComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule
],
providers: [CoursesService,EmailService],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
您导入了错误的Http
,而应该使用HttpClient
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
constructor(private http : HttpClient) {
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(response=>
{ console.log(response)
})
}
ngOnInit() {
}
}
如果您也想从硒中导入HttpClient
,您也可以这样做
import { HttpClient } from 'selenium-webdriver/http';
import { Component, OnInit } from '@angular/core';
import { HttpClient as Http } from '@angular/common/http';
@Component({
selector: 'posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
constructor(private http : Http) {
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(response=>
{ console.log(response)
})
}
ngOnInit() {
}
}
此外,您应该在HttpClientModule
中导入HttpModule
而不是app.module.ts
。
还有一件事,不要在构造函数中进行Http调用,这对构造函数是一种副作用,并且可能导致意外的问题,而是将其移入服务,将其注入组件中并从服务内部调用方法ngOnInit
生命周期挂钩