Angular中属性不存在错误,组件类数值变量赋值问题咨询
Let's break down the two key issues causing your errors and how to fix them:
1. Missing this. Reference in Component Method
In your JhiLoginModalComponent, you declared a as an instance property, but you're trying to assign it without using this. in the method() function. TypeScript treats a=3; as an attempt to use an undeclared local variable instead of accessing the component's instance property.
Fixed Component Code:
import { ..... @Component({ .... }) export class JhiLoginModalComponent implements OnInit { a: number; ngOnInit() { this.method(); } method() { this.a = 3; // Added `this.` to reference the instance property } }
2. Incorrect Component Class Reference in Test
Your test class uses ComponentClass which isn't the actual name of your component (it's JhiLoginModalComponent). This causes TypeScript to not recognize the component's properties/methods, leading to "property does not exist" errors in the test file.
Fixed Test Class Code (relevant parts):
import { JhiLoginModalComponent } from './path-to-your-component'; // Ensure correct import path describe('LoginComponent', () => { let comp: JhiLoginModalComponent; // Use actual component class name let fixture: ComponentFixture<JhiLoginModalComponent>; // Same here beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [JhiLoginModalComponent], // Make sure component is declared here // ... other test config }) })); // ... rest of your test code });
These changes should resolve both the component and test file errors. Always remember to use this. when accessing instance properties/methods in TypeScript classes, and ensure your test files reference the correct component class name.
内容的提问来源于stack exchange,提问作者Tester

