为啥Angular将成功的http post请求的结果显示为“未定义” [重复]

Posted

技术标签:

【中文标题】为啥Angular将成功的http post请求的结果显示为“未定义” [重复]【英文标题】:Why does Angular show result from successfull http post request as "undefined" [duplicate]为什么Angular将成功的http post请求的结果显示为“未定义” [重复] 【发布时间】:2019-10-17 18:23:04 【问题描述】:

我正在 Windows10 环境下开发 MEAN 堆栈应用程序,使用 Mongoose (v4.4.5) 连接到 MongoDB。我的代码中的一个 http post 请求成功执行并写入 MongoDB。但是从发布请求返回的响应在角度侧(在浏览器控制台中)显示为“未定义”。不过,这并不总是发生。有时响应实际上显示了写入 MongoDB 的确切内容(这是我一直希望看到的)。代码如下:

Angular 组件代码:

import  Component, OnInit, ViewChildren, Renderer2  from '@angular/core';
import  FormGroup, FormControl  from '@angular/forms';
import  Validators  from '@angular/forms';
import  contactUsInterface  from '../../models/contact-us';
import  HttpClient  from '@angular/common/http';
import  ContactUsService  from '../../services/contact-us.service';
import  ErrorMessageService  from '../../services/error-message.service';
import  Observable  from 'rxjs';

@Component(
  selector: 'app-contact-us',
  templateUrl: './contact-us.component.html',
  styleUrls: ['./contact-us.component.css'],
  )

export class ContactUsComponent implements OnInit 
  contactUsForm = new FormGroup(
    subject: new FormControl(''),
    message: new FormControl('', Validators.required),
    senderEmail: new FormControl('', [Validators.required, Validators.email]),
  );
  messageFromUser: contactUsInterface;
  response: any;
  successMessage = "Message successfully sent";
  displayMessage = this.successMessage;
  isVisible = "invisible"; //used for successMessage after on submitting form
  submitted = false;
  invalidControlArray = [];

  @ViewChildren("formControl") varInputBoxes;

  constructor(private renderer: Renderer2,
              private contactUsService: ContactUsService,
              private errorMessageService: ErrorMessageService) 

  ngOnInit() 

  onSubmit()
    this.submitted = true;
    if(this.contactUsForm.valid)
      this.messageFromUser = 
        subject: this.contactUsForm.value['subject'],
        message: this.contactUsForm.value['message'],
        senderEmail: this.contactUsForm.value['senderEmail'],
      ;
      this.saveMessage();
    
  ;

      saveMessage()
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => this.response = ...data,
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage));
//This is where the problem occurs.  "this.resopnse" below shows "undefined"
                    console.log('Response: ', this.response);
     ;

  get message()  return this.contactUsForm.get('message'); 
  get senderEmail()  return this.contactUsForm.get('senderEmail'); 

具有上述由 saveMessage() 调用的 addMessage 函数的 Angular 服务代码:

import  Injectable  from '@angular/core';
import  HttpClient, HttpHeaders, HttpErrorResponse, HttpResponse  from '@angular/common/http';
import  Observable, throwError  from 'rxjs';
import  catchError, map, tap, retry  from 'rxjs/operators';
import  contactUsInterface  from '../models/contact-us';

@Injectable(
  providedIn: 'root'
)

export class ContactUsService 
  private url = '/api/contactus';
  private result: any;
  message: string;

addMessage(messageFromUser: contactUsInterface): Observable<contactUsInterface> 
  return this.http.post<contactUsInterface>(this.url, messageFromUser)
  .pipe(retry(0));
;

constructor(private http: HttpClient)  
;

监听http请求的表达代码:

var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contact_us_message');

  router.route('/')
    .get(function(req,res,next)
      res.send(req)
    )
    .post(function(req,res,next)
      contactUsMessage.create(
        req.body, function(err,result)
          if (err) 
            next(err);
           else 
            res.send(result);
          
        
    )
  )

module.exports = router;

我原以为当 express 代码写入 MongoDB(这部分有效)并返回“结果”时,该结果是 addMessage(在 Angular 服务代码中)返回的内容,并分配给角组件。但这不是它的工作方式。

【问题讨论】:

【参考方案1】:

R. Richards 在 cmets 中发布的链接完美地解释了我的问题。我修改了我的角度组件代码如下(基本上,通过将 console.log 放在订阅部分中)并且它按预期工作。不过,如果您有类似的问题,R. Richards 提供的链接中选择的答案是必读的。

saveMessage()
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => this.response = ...data,
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage);
                    console.log('Response: ', this.response);
     
   )
 

【讨论】:

以上是关于为啥Angular将成功的http post请求的结果显示为“未定义” [重复]的主要内容,如果未能解决你的问题,请参考以下文章

为啥即使我已将 withCredentials 设置为 true,Angular 也不通过 POST 请求发送 cookie?

linux http请求不成功是为啥

Angular 为啥这个 HTTP 请求响应数组的长度未定义?

Angular 的 $http.post 不起作用,它的 $http... 也不起作用,但 jQuerys ajax 起作用。为啥?

在 Angular 中,如何使用 $location.path 作为 $http.post 成功回调进行重定向

Angular 11 - Spring Boot - MySQL:POST请求未成功创建数据库条目