简体   繁体   English

Angular 得到 http 响应

[英]Angular get http response

Hello i am at trying to learn some Angular things.您好,我正在尝试学习一些 Angular 的东西。 I am struggle with response of get from my api.我很难从我的 api 得到响应。 I am using also a spring boot in java.我还在 java 中使用 spring 引导。 Here is my service in angular:这是我在 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');
    }
}

this is my model class:这是我的 model class:

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;
    }
}

and here is my component to list values:这是我列出值的组件:


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');
  }

}

I am getting error with such output:我收到这样的 output 错误:


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. PS。 I am using angular 9. Thank's for any help我正在使用 angular 9。感谢您的帮助

There two ways you can inject your modules,有两种方法可以注入模块,

First one directly add into your service - providedIn: 'root' attribute第一个直接添加到您的服务中 - 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');
        }
    }

Or you can add from src/app/app.module.ts或者您可以从src/app/app.module.ts 添加

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

@NgModule({
  imports: [
    HttpClientModule
   ]
})

You can use 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();
    }
}

from you component you shall call:从您的组件中,您应该调用:

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);
});
}

From there you can adapt the tasks variable to your model.从那里您可以调整tasks变量以适应您的 model。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM