繁体   English   中英

从角度为6的service.ts返回undefined

[英]return undefined from service.ts in angular 6

我正在学习角度问题,并且在从服务中获取数据时遇到问题。 这是我的代码..

来自component.ts的代码

 import { Component, OnInit, Input } from '@angular/core';
 import { RegisterService } from '../services/register.service';

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

  contact:string;

  constructor(private data : RegisterService) { }

  ngOnInit() {
  }

  onSubmit(f){
  console.log('value from component.ts',f.value)

  if(f.valid){
  // "username":username,
  // "email":email,
  // "password":password,
  // "c_password":c_password,
  // "contact":contact,
  // "type":"user"
  // }
  console.log('type',f.value.type)
this.data.register(f.value.name,f.value.email,f.value.password,f.value.c_password,f.value.conatct,f.value.type)
.subscribe(res => {
  console.log(res)});
   }
  }

}

问题是从服务中获取数据。

来自service.ts的代码是

 import { Injectable } from '@angular/core';
 import { HttpHeaders, HttpClient } from '@angular/common/http';
 import { Body } from '@angular/http/src/body';

 @Injectable({
 providedIn: 'root'
 })


 export class RegisterService {

 API_URL = "http://..";

 constructor(private http: HttpClient) { }

 register(name,email,password,c_password,contact,type){

  let body ={
    "name":name,
    "email":email,
    "password":password,
    "c_password":c_password,
    "contact":contact,
    "type": 'user'
    }
    console.log('body from service',body);

    const headers = new HttpHeaders({
      "Accept" : 'application/json',
      "Content-Type" : 'application/json'
    })

return this.http.post(this.API_URL+"register",body,{headers :headers});
    }
   }

在这里,联系在控制台中返回未定义。 我是angular 6的新手。控制台的屏幕快照将添加到此处。 控制台的屏幕截图

问题是我拼错了“ f.value.contact”。 现在可以了

无需发送每个值给服务,只需发送f.value并重试。 检查控制台日志,您应该获取从component.ts传递到service.ts的所有数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM