[英]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.