Reputation: 121
Hi I am learning Angular now. I am making one simple web application using Angular and Spring Boot. I want to assign one 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);
}
When I try to assign this value it is not accepting. this.userCred.username = username; this.userCred.password = password;
the username and password which I am trying to assign is coming from the another component. I got these values 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)
Upvotes: 1
Views: 1013
Reputation: 17494
The error is coming because you need to initialize the variable which has only been declared in the given code.
try
export class UserRegistrationService {
public userCred : IUserCred = {
username: '',
password: ''
}
Also, create an interface
rather than class if you just want to define type
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;
}
Upvotes: 2