嗨,我现在正在学习Angular。我正在使用Angular和Spring Boot制作一个简单的web应用程序。我想给一个类的成员变量分配一个变量。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export class UserCred{
constructor (
public username: string,
public password: string
){}
}
@Injectable({
providedIn: 'root'
})
export class UserRegistrationService {
public userCred : UserCred
constructor(
private http: HttpClient
) { }
public createUser(user){
return this.http.post("http://localhost:8080/restapi/users",user);
}
public postUserCredientials(username, password){
console.log("Service login");
this.userCred.username = username;
this.userCred.password = password;
console.log("class username : ",this.userCred.username);
return this.http.post("http://localhost:8080/restapi/login", this.userCred);
}
当我尝试分配此值时,它是不可接受的。this.userCred.username=用户名;this.userCred.password=密码;
我试图分配的用户名和密码来自另一个组件。我使用Html文件中的[(ngModel(]获得了这些值
Error
ERROR TypeError: Cannot set property 'username' of undefined
at UserRegistrationService.postUserCredientials (user-registration.service.ts:30)
at LoginComponent.handleLogin (login.component.ts:39)
at LoginComponent_Template_button_click_8_listener (login.component.html:8)
at executeListenerWithErrorHandling (core.js:15216)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:15251)
at HTMLButtonElement.<anonymous> (platform-browser.js:582)
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27476)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
由于您需要初始化仅在给定代码中声明的变量,因此会出现错误。
尝试
export class UserRegistrationService {
public userCred : IUserCred = {
username: '',
password: ''
}
此外,如果您只想定义类型,请创建interface
而不是类
export interface IUserCred{ // try to add "I" to UserCred , it's a convention to know whether it's an interface or class.
username: string;
password: string;
}