- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在其中一个组件中运行 ng 测试时,我遇到了以下错误。
TypeError: Cannot read properties of undefined (reading 'dateOfLeaving')
error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({ }), matchedQueryIds: 0, references: Object({ }), ngContentIndex: null, childCount: 1, bindings: [ ], bindingFlags: 0, outputs: [ ], element: Object({ ns: '', name: 'app-view-employee', attrs: [ ], template: null, componentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs ...
TypeError: Cannot read properties of undefined (reading 'dateOfLeaving')
at ViewEmployeeComponent.ngOnInit (http://localhost:9876/_karma_webpack_/webpack:/src/app/employee/view/view-employee/view-employee.component.ts:22:17)
at checkAndUpdateDirectiveInline (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24503:1)
at checkAndUpdateNodeInline (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35163:1)
at checkAndUpdateNode (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35102:1)
at debugCheckAndUpdateNode (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36124:36)
at debugCheckDirectivesFn (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36067:1)
at Object.eval [as updateDirectives] (ng:///DynamicTestModule/ViewEmployeeComponent_Host.ngfactory.js:10:5)
at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36055:1)
at checkAndUpdateView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35067:1)
at callWithDebugContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36407:1)
employee.ts
export class Employee
{
id:number;
name:string;
dateOfBirth:string;
designation:string;
dateOfJoining:string;
workLocation:string;
email:string;
contactNo:number;
dateOfLeaving:string
constructor(){}
static getEmployee(id:number,
name:string,
dob:string,
designation:string,
dateOfJoining:string,
workLocation:string,
email:string,
contactNo:number,
dateOfLeaving:string
) :Employee
{
let emp = new Employee();
emp.id = id;
emp.name = name;
emp.dateOfBirth = dob;
emp.designation =designation;
emp.dateOfJoining = dateOfJoining;
emp.workLocation = workLocation;
emp.email = email;
emp.contactNo =contactNo;
emp.dateOfLeaving = dateOfLeaving
return emp;
}
}
view-component.ts
import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/service/common.service';
import { Employee } from '../../employee';
import { EmployeeService } from '../../employee.service';
@Component({
selector: 'app-view-employee',
templateUrl: './view-employee.component.html',
styleUrls: ['./view-employee.component.css']
})
export class ViewEmployeeComponent implements OnInit {
constructor(private employeeService: EmployeeService, private genericServices: CommonService) { }
emp:Employee;
availableLocations: string[] = [];
msg:string;
ngOnInit()
{
this.emp = this.employeeService.selectedEmployee;
if(this.emp.dateOfLeaving == null)
{
this.emp.dateOfLeaving = '';
}
this.genericServices.getWorkLocations().subscribe(
(resp:string[]) =>
{
this.availableLocations = this.availableLocations.concat( resp);
},
(err: any) =>
{
console.log("err" + err)
}
);
}
saveEmployee()
{
this.employeeService.updateEmployee(this.emp).subscribe(
(resp) =>
{
if(resp['status'] ==200)
{
let existingEmpIndex = this.employeeService.employees.findIndex((exitsEmp) => this.emp.id == exitsEmp.id);
this.employeeService.employees[existingEmpIndex] = this.emp;
this.msg = resp['message'];
}
},
(errMsg) =>
{
this.msg = errMsg['error']['errorMessage'];
}
)
}
}
查看-employee.component.spec.ts
import { HttpClientModule } from '@angular/common/http';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { CommonService } from 'src/app/service/common.service';
import { Employee } from '../../employee';
import { EmployeeService } from '../../employee.service';
import { ViewEmployeeComponent } from './view-employee.component';
describe('ViewEmployeeComponent', () => {
let component: ViewEmployeeComponent;
let fixture: ComponentFixture<ViewEmployeeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ViewEmployeeComponent ],
imports: [FormsModule, HttpClientModule],
providers: [EmployeeService, CommonService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ViewEmployeeComponent);
component = fixture.debugElement.componentInstance;
component.emp = new Employee();
component.emp.id =1;
component.emp.dateOfLeaving ="Today";
fixture.detectChanges();
});
it('should create', () => {
fixture.whenStable().then( ()=> {
fixture.detectChanges();
// expect(component).toBeTruthy();
})
});
});
员工服务.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { env } from 'process';
import { environment } from 'src/environments/environment';
import { URLMapping } from '../shared/URLMapping';
import { Employee } from './employee';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
employees:Array<Employee> =[];
selectedEmployee:Employee;
constructor(private httpClient: HttpClient)
{ }
fetchEmployee(emp:Employee)
{
console.log(emp)
// return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_VIEW, emp);
return this.selectedEmployee = emp;
}
createEmployee(emp:Employee)
{
return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_ADD, emp);
}
getEmployees()
{
return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_LIST, {});
}
updateEmployee(emp:Employee)
{
return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_SAVE, emp);
}
deleteEmployee(employees: Employee[]) {
return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_DELETE, employees);
}
}
id 属性也面临同样的问题。非常感谢任何引用或解决方案。
最佳答案
这里的问题是,只有当您调用 fixture.detectChanges()
并且您正在 ngOnInit() 中初始化
。因此在调用 emp
对象时,才会调用 Angular 生命周期方法fixture.detectChanges()
emp
对象属性
尝试下面的代码(view-employee.component.spec.ts
):
beforeEach(() => {
fixture = TestBed.createComponent(ViewEmployeeComponent);
fixture.detectChanges();
component = fixture.debugElement.componentInstance;
component.emp = new Employee();
component.emp.id =1;
component.emp.dateOfLeaving ="Today";
});
我还假设 this.employeeService.selectedEmployee
至少会返回空对象,否则您还必须模拟 EmployeeService
。
服务-
...
export class EmployeeService {
employees:Array<Employee> =[];
selectedEmployee:Employee = <Employee>{};
...
关于angular - 类型错误 : Cannot read properties of undefined (reading '<myvariable>' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69303457/
在使用我们开发团队的一些 as2 代码的过程中,我遇到了一些令人困惑的语句,其中变量被设置为自身。是否有一些我没有想到的冗余原因? 我的字面意思是这样的: function timeLine(x,w)
我最近将一堆表 PK 从 int 转换为 uniqueidentifier。现在在我的代码中,我将像这样替换某些检查: if (planDiagnosisID != 0) 与 if (planDiag
我对普通的旧式 JavaScript 和 JavaScript 框架(例如 Backbone.js、RequireJS 等)还很陌生。当我阅读并尝试理解从工作项目中获得的一些 JavaScript 文
在研究PowerShell脚本语言时,我尝试使用“写输出”命令来显示变量。 我使用另一种方法来创建变量。 例: $myvariable = 0x5555Set-Variable -Name myvar
我想知道用 PHP 编码时什么更好或更容易被接受。我被教导,在 Java 中,获取和设置变量的类方法应该以“get”和“set”为前缀。不过,我想知道的是,我是否应该在常规 PHP 函数上使用这些前缀
我创建了一个简单的代码 package main import ( "fmt" ) func main() { a := 5 b := &a Test(b) f
C++关于给Vector myVariable赋值 大家好。 我有这个结构 struct Point { int x,y; } 在我的 main.cpp 中我得到了这样的东西 int main() {
通常,问号的主要用途是用于条件句,x ? "is":“否”。 但我看到了它的另一种用法,但找不到对 ? 运算符这种用法的解释,例如。 public int? myProperty { get;
我一直在关注 perlmeme.org 上的教程,一些作者以下列方式声明变量: my $num_disks = shift || 9; # - no idea what the shift does
这是从服务器向客户端发送 ArrayList 的程序的一部分。我想删除这段代码最后一行的警告: 客户端代码: Socket s; (...) // A server is sending a list
我正在尝试通过 ADO 使用参数化查询。执行 Command 对象会引发错误: Must declare the variable '@filename' 我使用CreateParameter/App
我收到错误消息: Error: object 'x' not found 或者更复杂的版本,比如 Error in mean(x) : error in evaluating the argument
我试图访问内部类中的 h 变量,但错误不断出现“无法为最终变量 h 赋值”。我尝试了快速修复,它指示我“将 h 转换为最终一个元素数组”。这是什么意思? int Update () { fin
在其中一个组件中运行 ng 测试时,我遇到了以下错误。 TypeError: Cannot read properties of undefined (reading 'dateOfLeaving')
在我看来,我有一个输入、一个跨度和一个按钮,如下所示: {{ phoneNumber}} 在文本框中输入时,span 的内容按预期阅读更新。但是当点击按钮时,phoneNumber
总的来说,我对 javascript 和前端编码还很陌生。我正在开发一个代码笔,并试图理解代码中的所有内容,以便我可以根据自己的需要进行修改。 有一个函数: function checkTiles()
我在Visual Studio 2012中使用WPF + XAML + MVVM时遇到此错误。 Cannot resolve symbol ”MyVariable“ due to unknown Da
我想将一个字符串回显到 /etc/hosts 文件中。该字符串存储在名为 $myString 的变量中。 当我运行以下代码时,回显为空: finalString="Hello\nWorld" sudo
我是一名优秀的程序员,十分优秀!