如何在角度5的后置响应后从restAPI发送数据?

时间:2018-04-22 13:59:34

标签: node.js angular rxjs observable angular-http

我从服务器发送的json对象的输出有问题,由于某种原因我无法获取并显示服务器响应中包含的消息。我究竟做错了什么?谢谢你的帮助。 以下是我的申请代码。

服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { User } from './user';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import { ResponseObject } from './response-object';

@Injectable()
export class MntApiService {

  private mntAPI = 'http://localhost:3000';

  constructor(private _http: HttpClient) {
  }
  getUsers(): Observable<any> {
    return this._http.get<any>(this.mntAPI + '/users');
  }
  addUser(email: string, password: string): Observable<any> {
    return this._http.post<any>(this.mntAPI + '/signup', { email, password }, )
    .map((response: Response) => response);
  }
}

成分:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';

import { MntApiService } from '../mnt-api.service';

import { User } from '../user';
import { ResInterceptor } from '../res-interceptor';

@Component({
  selector: 'app-signup-page',
  templateUrl: './signup-page.component.html',
  styleUrls: ['./signup-page.component.scss']
})
export class SignupPageComponent implements OnInit {
  users: any = [];
  myForm: FormGroup;
  response: {
    body: {
      succes: boolean,
      message: string,
      status: number
    }
  };
  constructor(
    private mntApiService: MntApiService,
    private fb: FormBuilder,
    public routes: Router) {
  }

  ngOnInit() {
    this.initForm();
  }



  private initForm(): void {
    this.myForm = this.fb.group({
      // type: null,
      email: [null, [
        Validators.required, Validators.email
      ]],
      password: [null, [
        Validators.required
      ]]
    });
  }

  isControlInvalid(controlName: string): boolean {
    const control = this.myForm.controls[controlName];

    const result: boolean = control.invalid && control.touched;

    return result;
  }

  addUser() {
    const val = this.myForm.value;
    const controls = this.myForm.controls;
    if (this.myForm.invalid) {
      Object.keys(controls)
        .forEach(controlName => controls[controlName].markAsTouched());
      return;
    } else {
      val.email = val.email.trim();
      val.password = val.password.trim();
      if (!val.email && !val.password) {
        return;
      }
       this.mntApiService.addUser(val.email, val.password)
        .subscribe(user => {
          this.users.push(user);
        },
      response => { this.response = response; });
      console.log(this.response);
      return;

    }
  }
}

component.html

<div class="container pt-5">
  <form [formGroup]="myForm">
    <div class="form-group">
      <label for="email">Email address</label>
      <small class="form-text text-danger">
        {{response?.body.message}}
      </small>
      <input formControlName="email" type="email" class="form-control" id="email" placeholder="Enter email" autocomplete="email">
      <small *ngIf="isControlInvalid('email')" class="form-text text-danger">неправельный формат почты</small>
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input formControlName="password" type="password" class="form-control" id="password" placeholder="Password"
        autocomplete="current-password">
      <small *ngIf="isControlInvalid('password')" class="form-text text-danger">это поле не может быть пустым</small>

    </div>
    <button (click)="addUser()"  class="btn btn-primary">Submit
    </button>
  </form>

</div>

和我的节点服务器代码:

app.post('/signup', (req, res) => {

  let sql = 'SELECT email FROM users WHERE email = ?';
  let emailBody = [req.body.email];

  config.query(sql, emailBody, (err, userEmail) => {
    const errResponse = {
      sacces: false,
      message: 'Почта занята'
    };
    const rightResponse = {
      'sacces': true,
      'message': 'Пользователь создан',
      'status': 201
    };
    if (userEmail.length < 0) {
      res.status(409).send(errResponse);
      console.log('mail exist!!!!');
      return;
    } else {
      bcrypt.hash(req.body.password, 10, (err, hash) => {
        if (err) {
          return res.status(500).json({
            error: err
          });
        } else {
          let sql = 'INSERT INTO users ( email, password) VALUES ( ?, ?)';
          let email = req.body.email;
          let password = hash;
          let body = [email, password];
          config.query(sql, body, (err) => {
            if (err) {
              res.json({
                "message": 'SQL Error'
              });
            } else {
              //res.sendStatus(201);
              res.status(201).send(rightResponse);
              // res.status(201).json({
              //   'message': "Спасибо за регестрацию"
              // });
              console.log('User created');
              return;
            }
          });
        }
      });
    }
  });
});

请帮助谁,我是新手开发者。

1 个答案:

答案 0 :(得分:0)

这是您的代码的一部分

   this.mntApiService.addUser(val.email, val.password)
    .subscribe(user => {
      this.users.push(user);
    },
  response => { this.response = response; });

您在这里做的是传递subscribe方法2参数。 第一个参数是这个函数

user => {
          this.users.push(user);
        }

第二个参数是这个函数

response => { this.response = response; }

作为第二个参数传递给subscribe的函数在发生错误时执行,我想这不是你想要的。

这样的实现可能会为你做到这一点

   this.mntApiService.addUser(val.email, val.password)
    .subscribe(response => {
      response => { this.response = response; });
      // this.users.push(user); CHECK THIS LINE - YOU ARE NOT RECEIVING A USER FROM THE SERVER BUT A MESSAGE
    };