为使用界面创建的对象赋值?



自从我试图找出创建对象的解决方案以来已经有几个小时了。 在网上找不到任何东西。我无法在构造函数之外访问 user1。请帮忙。

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-first-folder',
templateUrl: './first-folder.component.html',
styleUrls: ['./first-folder.component.css']
})
export class FirstFolderComponent implements OnInit {
nameVar:string;
passwordVar:string;
@Input() test:string;

constructor() {
interface UserInface{
name:string,
password:string
};
var user1: UserInface;
}

ngOnInit() {
}
//function for button click
submitBtn(){ 
**//I am getting error here because i am trying to assign values to object.**
**//error "Property 'user1' does not exist on type "**
this.user1.name = this.nameVar;
this.user1.password = this.passwordVar

}
}

在类外制作interfaceexport它,然后在class内使用它。见下文,我已经在类外制作了interface并将其导出。

堆栈闪电战演示

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-first-folder',
templateUrl: './first-folder.component.html',
styleUrls: ['./first-folder.component.css']
})
export class FirstFolderComponent implements OnInit {    
nameVar:string;
passwordVar:string;
@Input() test:string;
user1: UserInface;

constructor() {
this.user1 = {name: '', password: ''}; // You can remove this line if you don't want 
}
ngOnInit() {}
submitBtn(){ 
this.user1 = {name: 'Surjeet', password: 'Singh'};
}
}
// paste this code at the end of the component
export interface UserInface{
name:string,
password:string
};
import { Component, OnInit, Input } from '@angular/core';
export interface UserInface{
name:string,
password:string
};
@Component({
selector: 'app-first-folder',
templateUrl: './first-folder.component.html',
styleUrls: ['./first-folder.component.css']
})
export class FirstFolderComponent implements OnInit {
nameVar:string;
passwordVar:string;
user1: UserInface;
@Input() test:string;
constructor() {
}

ngOnInit() {
}
//function for button click
submitBtn(){ 
**//I am getting error here because i am trying to assign values to object.**
**//error "Property 'user1' does not exist on type "**
this.user1.name = this.nameVar;
this.user1.password = this.passwordVar

为什么你的解决方案不起作用?

您在构造函数中定义了var user1,它是构造函数的局部变量。您可以创建user1作为类成员(类属性(。因此,如果您希望它在类的其他方法中可用,则必须将其用作构造函数中的this.user1

您需要以下代码:

import { Component, OnInit, Input } from '@angular/core';
interface UserInface{
name:string,
password:string
};
@Component({
selector: 'app-first-folder',
templateUrl: './first-folder.component.html',
styleUrls: ['./first-folder.component.css']
})
export class FirstFolderComponent implements OnInit {
user1: UserInface = {};
nameVar:string;
passwordVar:string;
@Input() test:string;
//function for button click
submitBtn(){ 
this.user1.name = this.nameVar;
this.user1.password = this.passwordVar
}
}

请注意,在 user1 的初始化处分配空对象。您也可以在构造函数中执行此操作,例如:

constructor() {
this.user1 = {};
}

最新更新