简体   繁体   English

如何在 Type Script Angular 中为类的成员变量赋值

[英]How to assign value to the member variable of a Class in Type Script Angular

Hi I am learning Angular now.嗨,我现在正在学习 Angular。 I am making one simple web application using Angular and Spring Boot.我正在使用 Angular 和 Spring Boot 制作一个简单的 Web 应用程序。 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.username = 用户名; this.userCred.password = password; this.userCred.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我使用 [(ngModel)] 从 Html 文件中获得这些值

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)

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另外,如果您只想定义类型,请创建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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM