0

我希望你一切都好。

我有一个问题,我不知道如何解决它。我有一个带有食谱的 API,并且我设法在前端显示它们,但现在我无法使发布路由工作以在我的数据库中成功插入新食谱。如果有人能告诉我该怎么做,我将不胜感激。

节点:

app.post("/recipes", (req, res) => {
  recipe = new Recipe({
    _id: req.body._id,
    title: req.body.title,
    image: req.body.image,
    description: req.body.description,
    calories: req.body.calories,
    cookingTime: req.body.cookingTime,
  });

  recipe.save(() => {
    res.json(recipe);
  });
});

打字稿服务添加配方

// Add recipe
  post(uri: string, payload: Object) {
    return this.http.post(`${this.url}/${uri}`, payload);
  }

打字稿添加配方

 ngOnInit(): void {
    this.addRecipeForm = this.formBuilder.group({
      _id: new FormControl(''),
      title: new FormControl(''),
      image: new FormControl(''),
      description: new FormControl(''),
      calories: new FormControl(''),
      cookingTime: new FormControl(''),
    });
  }
export class RecipeModel {
  _id!: String;
  title!: String;
  image!: String;
  description!: String;
  calories!: String;
  cookingTime!: String;
}

显示食谱的食谱 HTML

<div *ngFor="let recipe of data">
      <p>
        {{ recipe.title }}
      </p>
      <img src="{{ recipe.image }}" alt="" />
      <p>{{ recipe.description }}</p>
      <p>{{ recipe.calories }}</p>
      <p>{{ recipe.cookingTime }}</p>
      <p>{{ recipe._id }}</p>

       <button routerLink="/add">Add a new recipe here</button>
    </div>

我现在要做的是按下按钮添加新配方并插入值,然后在我的数据库和 UI 中查看配方,我该如何管理它,非常感谢您的时间。

问候

4

1 回答 1

0

首先,你必须使用来自 RxJS 的 Observables(查看更多关于它们)在 CRUD 操作之后刷新你的食谱列表。例如,如果你从不使用它,我建议你先阅读使用 RxJS 进行反应式编程的基础知识。所以 POST 请求必须是这样的:

// Add recipe
addRecipe(uri: string, payload: Object): Observable<RecipeModel> {
  return this.http.post(`${this.url}/${uri}`, payload).pipe(
    map((response: RecipeModel ) => response as RecipeModel ),
    catchError( error => {
      return throwError(error);
    }
   )
  );
 }

然后你可以简单地订阅这个方法:

this.myRecipeService.addRecipe(myUri, myPayload).subscribe(
  responseFromServer => {
    refreshMyRecipes(); // or refresh basing in your server response
  }
)

此方法将向您所需的 URI 发送一个 POST 请求,当服务器结束处理您的请求时,anon 方法将执行刷新您的配方列表。

于 2021-08-12T12:34:57.183 回答