我正在尝试使用Angular / Typescript在服务类中创建一个简单的帖子 我的IDE没有给我任何错误,但是当我调用该函数时,我得到了未定义。我不确定问题的根源。我做了一些研究,似乎问题可能是我正在导入的HttpClient,但我找不到任何相关的东西。
前端功能:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ServiceClassAuth {
auth: any;
user: any;
constructor(private http: HttpClient) {}
signinUser(user) {}
login(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
const loginUrl = 'http://localhost:3000/login';
return this.http.post(loginUrl, user, {
headers: headers
}).map((res: Response) => res.json());
}
}
调用服务的组件:
import { Component, OnInit } from '@angular/core';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA
} from '@angular/material';
import { Inject } from '@angular/core';
import { ServiceClassAuth } from '../service/service-class-auth';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css'],
providers: [ServiceClassAuth]
})
export class SigninComponent implements OnInit {
username: String;
password: String;
ngOnInit() {}
constructor(
public dialogRef: MatDialogRef < SigninComponent > ,
@Inject(MAT_DIALOG_DATA) public data: any,
private authService: ServiceClassAuth) {}
onNoClick(): void {
this.dialogRef.close();
}
loginSubmit(postValues): void {
const user = {
'usr': postValues.value.usrname,
'psw': postValues.value.psw
}
const res = this.authService.login(user).subscribe(res => {
if (res.success) {
} else {
//DO ALERT
}
});
}
}