Angular上的帖子请求问题

时间:2017-12-15 17:19:20

标签: node.js angular post

我目前正在尝试更新用户数据。所以这是我的html表单

        <form (submit)="onUserUpdateSubmit()"class="form-horizontal" role="form">
      <div class="form-group">
        <label class="col-lg-3 control-label">Username:</label>
        <div class="col-lg-8">
          <input class="form-control"  [(ngModel)]="username" name="username"  type="text">
        </div>
      </div>
      <div class="form-group">
        <label class="col-lg-3 control-label">Email:</label>
        <div class="col-lg-8">
          <input class="form-control"  [(ngModel)]="email" name="email" type="text">
        </div>
      </div>
        <label class="col-md-3 control-label"></label>
        <div class="col-md-8">
          <input class="btn btn-primary" value="Save Changes" type="submit">
          <span></span>
          <input class="btn btn-default" value="Cancel" type="reset">
        </div>
      </div>
    </form>

然后我创建了updateservice.ts,我只是向api发送请求,如下所示

updateProfile(user){
   console.log("update profile func", user)
   let headers = new Headers();
  this.authToken = this.authService.loadToken();
  headers.append('Authorization', this.authToken)
  headers.append('Content-Type', 'application/json');
  return this.http.post('http://localhost:17696/users/update', user, {headers:headers})
    .map(res => res.json())
}

但是在这里我卡住了因为我的浏览器在开发者控制台中给了我错误 我尝试使用用户名和电子邮件来控制我的对象。虽然我得到了用户名:false,但它很好。而且我也是console.log我的对象叫做user但是它未定义。 这是profile.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service'
import { ValidateService } from '../../services/validate.service'
import { FlashMessagesService } from 'angular2-flash-messages'
import { Router } from '@angular/router'
import { UpdateService } from '../../services/update.service'

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  user: Object;
  userToUpdate: Object;
  username: String;
  email: String;
  avatar: String;

  constructor(private authService: AuthService,
     private router: Router,
     private flashMessage:FlashMessagesService,
     private validateService : ValidateService,
     private updateService: UpdateService) { }

  ngOnInit() {
    this.authService.getProfile().subscribe(profile=>{
      this.user = profile.user;
    },
    err=>{
      console.log(err);
      return false;
    });
  }

  onUserUpdateSubmit(){
    const userToUpdate ={
      username:this.username,
      email:this.email,
    }
    console.log(userToUpdate)
    //required fields
    if(!this.validateService.validateUserUpdate(userToUpdate)){
      this.flashMessage.show('Please, fill in all fields', {cssClass: 'alert-danger', timeout:3000});
      return false;
    }

    //validate email    
    if(!this.validateService.validateEmail(userToUpdate.email)){
      this.flashMessage.show('Please, enter correct email', {cssClass: 'alert-danger', timeout:3000});      
      return false;
    }



    this.updateService.updateProfile(userToUpdate).subscribe(data=>{
      console.log( "its from update service profilecomponent.ts")
      console.log(data)
      if(data/*.success*/){ //commented cause response doesnt have property success but still registering user without displaying the flash message
        this.flashMessage.show('You successfuly changed your info', {cssClass: 'alert-success', timeout:3000});
        this.router.navigate(['/profile'])
      }else{
        this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout:3000});
        this.router.navigate(['/profile'])
      }
    });
  }

}

image of errors

1 个答案:

答案 0 :(得分:0)

从我所看到的,你有一个同名变量的两个不同副本,这就是造成混淆的原因

在您正在执行的更新方法的开头

const userToUpdate ={
  username:this.username,
  email:this.email,
}

const是一个块作用域变量,意味着您在此方法中创建一个名为userToUpdate的副本。

您要传递给服务更新方法的变量是

this.userToUpdate
正如你在代码中看到的那样

this.updateService.updateProfile(this.userToUpdate)

通过执行此操作,您将使用在组件上下文中声明的公共属性

因此,要解决您的问题,您有两种选择。您可以通过执行

将所需的值设置为组件属性
this.userToUpdate ={
  username:this.username,
  email:this.email,
}

或者您将本地userToUpdate传递给您的服务电话

this.updateService.updateProfile(userToUpdate)