我正在开发一个带有角的配方应用程序,并试图使用HTTP设置与后端服务的通信。我一直跟随着角文档来设置这个,这是链接https://angular.io/guide/http#sending-data-to-a-server。当我添加代码以发出POST请求时,我会得到以下错误:
ERROR Error: Uncaught (in promise): TypeError: factory.factory is not a function
TypeError: factory.factory is not a function
at getNodeInjectable (core.js:3913)
at searchTokensOnInjector (core.js:3849)
at getOrCreateInjectable (core.js:3771)
at Module.ɵɵdirectiveInject (core.js:13730)
at NodeInjectorFactory.FormComponent_Factory [as factory] (form.component.ts:14)
at getNodeInjectable (core.js:3913)
at instantiateRootComponent (core.js:7837)
at createRootComponent (core.js:18351)
at ComponentFactory$1.create (core.js:22287)
at ViewContainerRef.createComponent (core.js:10127)
at resolvePromise (zone-evergreen.js:798)
at resolvePromise (zone-evergreen.js:750)
at zone-evergreen.js:860
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27126)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at drainMicroTaskQueue (zone-evergreen.js:569)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
at invokeTask (zone-evergreen.js:1621)我不知道如何修复这个错误,因为我已经尝试了很长一段时间了。下面是启动POST请求的代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
import { Addedrecipes } from './addedsoups';
import { RecipesService } from './recipes.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
providers: [RecipesService],
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
sections = ['Bread', 'Soup', 'Cakes'];
recipe = { name: '', ingredients: '', description: '', section: this.sections[0] };
Form: FormGroup;
addedrecipes: any;
constructor(private fb: FormBuilder, private recipesService: RecipesService) { }
ngOnInit() {
this.Form = new FormGroup({
name: new FormControl(this.recipe.name, [
Validators.required,
Validators.minLength(1)
]),
ingredients: new FormControl(this.recipe.ingredients, [
Validators.required,
Validators.minLength(10)
]),
description: new FormControl(this.recipe.description, [
Validators.required,
Validators.minLength(20)
]),
section: new FormControl(this.recipe.section, Validators.required)
})
}
add(name: string, description: string, ingredients: string): void {
name = name.trim();
description = description.trim();
ingredients = ingredients.trim();
if (!name || !description || !ingredients) {
return;
}
// The server will generate the id for this new hero
const newRecipe: Addedrecipes = { name, description, ingredients } as Addedrecipes;
console.log("this works");
this.recipesService
.addRecipe(newRecipe)
.subscribe(recipe => this.addedrecipes.push(recipe));
}
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.Form.value);
}
}以下是我提出请求的服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Addedrecipes } from './addedsoups';
import { HttpErrorHandler, HandleError } from '../http-error-handler.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'my-auth-token'
})
};
// @NgModule({
// declarations: [],
// imports: [BrowserModule],
// providers: [HttpErrorHandler],
// bootstrap: []
// })
// @Injectable({
// providedIn: 'root',
// })
@NgModule({
providers: [HttpErrorHandler]
})
@Injectable ()
export class RecipesService {
recipeUrl = 'api/recipe'; // URL to web api
private handleError: HandleError;
constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('RecipesService');
{ }
}
addRecipe(addedrecipes: Addedrecipes): Observable<Addedrecipes> {
return this.http.post< Addedrecipes>(this.recipeUrl, addedrecipes, httpOptions)
.pipe(
catchError(this.handleError("addRecipe", addedrecipes))
);
}
}对如何修复发生的错误有什么想法吗?如有任何意见/建议,我们将不胜感激。提前谢谢你。
发布于 2021-06-08 17:59:54
根据注释和代码,您已经有点混乱了。
首先,您的服务不应该有@NgModule声明:它是一个服务,而不是一个模块。此外,由于您的服务不是providedIn: "root",所以实际上需要在模块中提供它。
假设AppModule是该组件和该服务都存在的位置,那么您应该有一个类似于以下内容的app.module.ts:
@NgModule({
declarations: [FormComponent],
imports: [BrowserModule],
providers: [HttpErrorHandler, RecipesService],
})
export class AppModule {}据我所知,你的form.component.ts很好。
在recipes.service.ts中,需要完全省略NgModule声明:
@Injectable ()
export class RecipesService {
recipeUrl = 'api/recipe'; // URL to web api
private handleError: HandleError;
constructor(private http: HttpClient,
httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('RecipesService');
}
addRecipe(addedrecipes: Addedrecipes): Observable<Addedrecipes> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'my-auth-token'
})
};
return this.http.post< Addedrecipes>(this.recipeUrl, addedrecipes, httpOptions)
.pipe(
catchError(this.handleError("addRecipe", addedrecipes))
);
}
}我很确定这是怎么回事是你的错误信息。如果您查看堆栈跟踪,它实际上是在抱怨注入的依赖项--堆栈跟踪中引用实际代码的行是NodeInjectorFactory.FormComponent_Factory [as factory] (form.component.ts:14)。这表明您的API调用本身没有什么问题.或者至少,它甚至还没有达到那个程度。问题在于您如何声明您的服务,并将其呈现为要注入的角度。
提供服务的最简单方法是通过默认设置。当使用角CLI生成新服务时,它将创建一个全局可用的服务:
@Injectable({
providedIn: "root"
})如果您不希望您的服务在全球范围内可用,您可以像在您的示例中那样删除它。但是,副作用是,无论您想要实际使用该服务,都必须使用模块声明中的providers数组显式地提供该服务。
https://stackoverflow.com/questions/67879820
复制相似问题