Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class.
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);
}
I faced an issue while trying to assign the value:
this.userCred.username = username; this.userCred.password = password;
The values for username and password that I attempted to assign are sourced from another component. These values were obtained using [(ngModel)] from the HTML file.
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)