解析 json angular 请求放

Parse json angular request put

我的 put 请求有点问题。在我的nodejs中,如果请求成功,我会像这样向angular发送一条消息json。

res.json({ success: true, message: 'Success'})

在 angular 中,我创建了一个请求以在添加或修改数据库中的对象后捕获此消息。如果我添加对象,我可以从 nodejs 捕获此消息,并且可以解析此消息,但如果我想修改一个对象,我无法解析 json 并且出现此消息错误。

Classe.service.ts

updateClasse(room, id) {
   const uri = 'http://localhost:4000/api/classes/update/' + id;
   const obj = { room: room };

   this.http.put(uri, obj).subscribe(
     (res:any)=> {
       this.okReq = res.message;
       return this.okReq;
     });
}

Classe.component.ts

  updateClasse(room) {
    this.route.params.subscribe(params => {
       this.service.updateClasse(room, params['id']);
     });
    this.router.navigate(['/classes']);
 }

Classe.html

{{ okReq }}
<form [formGroup]="angForm">
  <div class="form-group">
    <label class="col-md-4">Classe Name</label>
    <input type="text" class="form-control" formControlName="room" #room [(ngModel)] = "classe.room"/>
  </div>
  <div class="form-group">
    <button (click)="updateClasse(room.value)" class="btn btn-primary">Update</button>
  </div>
</form>

只需将您的回复 type 更改为 any

 this.http.put(uri, obj).subscribe(
     (res:any)=> {
       console.log(res.message)
});

您可以使用通用类型来设置 http 操作返回值的类型。假设您已经有一个 MessageResponse 类型:

interface MessageResponse {
  success: boolean;
  message: string;
}

现在您可以将其用作 .put 的通用参数:

this.http.put<MessageResponse>(uri, obj)

现在 res 被假定为 MessageResponse 类型,这将允许您访问 res.message 作为字符串值。


顺便说一下,我不会在您的服务中使用 .subscribe。相反,我会在您需要实际调用 http 请求时使用它,例如在依赖于响应的组件或其他服务中。