简体   繁体   中英

return undefined from service.ts in angular 6

I'm learning angular and I have a problem with getting data from service. This is my code ..

code from 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)});
   }
  }

}

The problem is getting data from service.

code from service.ts is

 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});
    }
   }

Here contact is return undefined in console. I'am a newbie in angular 6. The screenshot of console is adding here. The screenshot of console

The issue was I miss-spelled "f.value.contact". Now it is ok

Instead of sending every value to service, just send f.value and try again. check your log of console you should get every data that is passed from component.ts to service.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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