typescript Angular 获取http响应

ee7vknir  于 2023-02-17  发布在  TypeScript
关注(0)|答案(2)|浏览(195)

你好,我在尝试学习一些Angular 的东西。我从我的API得到的响应斗争。我也在使用java中的 Spring Boot 。这里是我的Angular 服务:

import {HttpClient} from "@angular/common/http";
import {Injectable} from "@angular/core";

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) {
    }

    getTasks() {
        return this.http.get('/api/tasks');
    }
}

这是我的模型类:

export class Task {
    public id: number;
    public name: string;
    public completed: boolean;
    public dueDate: string;

    constructor(id: number, name: string, completed: boolean, dueDate: string) {
        this.id = id;
        this.name = name;
        this.completed = completed;
        this.dueDate = dueDate;
    }
}

这是我的组件来列出值:

import { Component, OnInit } from '@angular/core';
import {Task} from "../task.model";
import {TaskService} from "../task.service";

@Component({
  selector: 'app-tasks-list',
  templateUrl: './tasks-list.component.html',
  styleUrls: ['./tasks-list.component.css']
})
export class TasksListComponent implements OnInit {

    tasks: Task[] = [];

  constructor(private taskService: TaskService) { }

  ngOnInit()  {
      return this.taskService.getTasks().subscribe(
          (tasks: any[]) => {
              this.tasks = tasks
          },
          (error) => console.log(error)
      )
  }

  getDueDateLabel(task:Task) {
      return task.completed ? 'badge-success' : 'badge-primary';
  }

  onTaskChange(event, task) {
      // this.taskService.saveTask(task, event.target.checked).subscribe();
      console.log('Task has changed');
  }

}

我得到这样的输出错误:

core.js:4442 ERROR NullInjectorError: R3InjectorError(AppModule)[TaskService -> HttpClient -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:4200/vendor.js:11749:27)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at injectInjectorOnly (http://localhost:4200/vendor.js:11635:33)
    at Module.ɵɵinject (http://localhost:4200/vendor.js:11639:57)
    at Object.TaskService_Factory [as factory] (http://localhost:4200/main.js:251:138)
    at R3Injector.hydrate (http://localhost:4200/vendor.js:22036:35)
    at R3Injector.get (http://localhost:4200/vendor.js:21857:33)
    at NgModuleRef$1.get (http://localhost:4200/vendor.js:34997:33)
defaultErrorLogger @ core.js:4442
handleError @ core.js:4490
(anonymous) @ core.js:28164
invoke @ zone-evergreen.js:364
run @ zone-evergreen.js:123
runOutsideAngular @ core.js:27431
(anonymous) @ core.js:28164
invoke @ zone-evergreen.js:364
onInvoke @ core.js:27504
invoke @ zone-evergreen.js:363
run @ zone-evergreen.js:123
(anonymous) @ zone-evergreen.js:857
invokeTask @ zone-evergreen.js:399
onInvokeTask @ core.js:27492
invokeTask @ zone-evergreen.js:398
runTask @ zone-evergreen.js:167
drainMicroTaskQueue @ zone-evergreen.js:569
Promise.then (async)
scheduleMicroTask @ zone-evergreen.js:552
scheduleTask @ zone-evergreen.js:388
scheduleTask @ zone-evergreen.js:210
scheduleMicroTask @ zone-evergreen.js:230
scheduleResolveOrReject @ zone-evergreen.js:847
then @ zone-evergreen.js:979
bootstrapModule @ core.js:28092
zUnb @ main.ts:11
__webpack_require__ @ bootstrap:79
0 @ main.js:11
__webpack_require__ @ bootstrap:79
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
main.ts:12 NullInjectorError: R3InjectorError(AppModule)[TaskService -> HttpClient -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:4200/vendor.js:11749:27)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at R3Injector.get (http://localhost:4200/vendor.js:21868:33)
    at injectInjectorOnly (http://localhost:4200/vendor.js:11635:33)
    at Module.ɵɵinject (http://localhost:4200/vendor.js:11639:57)
    at Object.TaskService_Factory [as factory] (http://localhost:4200/main.js:251:138)
    at R3Injector.hydrate (http://localhost:4200/vendor.js:22036:35)
    at R3Injector.get (http://localhost:4200/vendor.js:21857:33)
    at NgModuleRef$1.get (http://localhost:4200/vendor.js:34997:33)

PS.我用的是Angular 9.谢谢你的帮助

6vl6ewon

6vl6ewon1#

有两种方法可以注入模块,
第一个直接添加到您的服务中-providedIn: 'root'属性

import {HttpClient} from "@angular/common/http";
   import {Injectable} from "@angular/core";
   
    @Injectable({
       providedIn: 'root'
    })

    @Injectable()
    export class TaskService {
    
        constructor(private http: HttpClient) {
        }
    
        getTasks() {
            return this.http.get('/api/tasks');
        }
    }

或者您可以从 src/app/app.module.ts 添加

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
   ]
})
hxzsmxv2

hxzsmxv22#

您可以使用promis:

import {HttpClient} from "@angular/common/http";
import {Injectable} from "@angular/core";

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) {
    }

    getTasks() {
        return this.http.get('/api/tasks').toPromis();
    }
}

从您的组件中,您应调用:

public tasks = [];

ngOnInit(){
 this.loadTasks();
}

loadTasks() {
  this.taskService.getTasks().then((response) => {
    console.log(response);
    this.task = JSON.parse(JSON.stringify(response)); //if you server returns json data
}).catch((error) => {
  console.log(error);
});
}

从这里您可以调整tasks变量以适应您的模型。

相关问题