简体   繁体   English

类型错误:无法读取未定义的 angular7 的属性“_id”

[英]TypeError: Cannot read property '_id' of undefined angular7

I have a component employee I am trying to create a form, for which I have created "employee component", "employee service" and "employee model"我有一个组件员工我正在尝试创建一个表单,为此我创建了“员工组件”、“员工服务”和“员工模型”

In employee.component.html I have below form在 employee.component.html 我有以下表格

 <form #employeeform="ngForm" (ngSubmit)="onSubmit(employeeform)">
          <input type="hidden" name="_id"  [(ngModel)]="employeeservice.selectedEmployee._id" #_id="ngModel"/>
        </form>

In employee.component.ts I have below code在 employee.component.ts 我有下面的代码

 import { Component, OnInit } from '@angular/core';
 import { EmployeeService } from '../shared/employee.service';

 @Component({
    selector: 'app-employee',
    templateUrl: './employee.component.html',
    styleUrls: ['./employee.component.css'],
    providers : [EmployeeService]
 });

 export class EmployeeComponent implements OnInit {
    constructor(private employeeservice : EmployeeService) { }
      ngOnInit() {
      }
   }

This is my employee.service.ts file which I have imported in employee component这是我在员工组件中导入的 employee.service.ts 文件

 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { Employee } from './employee.model';

 @Injectable({
   providedIn: 'root'
 })
 export class EmployeeService {
   selectedEmployee : Employee;
   employees: Employee[];

   constructor() { }
 }

Here is my employee.model.ts which I have imported in employee service这是我在员工服务中导入的 employee.model.ts

 export class Employee {
     _id: string;
     name: string;
     position : string;
     office : string;
     salary : number;
 }

I am getting the below error in my browser console when I run the command "ng serve"当我运行命令“ng serve”时,我的浏览器控制台出现以下错误

 EmployeeComponent.html:9 ERROR TypeError: Cannot read property '_id' of undefined
at Object.eval [as updateDirectives] (EmployeeComponent.html:9)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
at checkAndUpdateView (core.js:23307)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)
at callViewAction (core.js:23548)
at execComponentViewsAction (core.js:23490)
at checkAndUpdateView (core.js:23313)

Am I missing any imports that a form needs or what could be the error.我是否缺少表单需要的任何导入或可能是什么错误。 I am a beginner and trying to learn angular.我是初学者,正在尝试学习角度。 I have googled for the solution, but I couldn't find any relevant solution.我用谷歌搜索了解决方案,但找不到任何相关的解决方案。 Please help me out请帮帮我

I would recommend you to create an instance of the employee inside of the EmployeeComponent, and every time when you open the component - retrieve it from the service and target it at the html code.我建议您在 EmployeeComponent 中创建一个员工实例,并且每次打开该组件时 - 从服务中检索它并将其定位到 html 代码。 Something like:就像是:

export class EmployeeComponent implements OnInit {
    employee: Employee;

    constructor(private employeeservice : EmployeeService) { 
      this.employee = employeeservice.getSelectedEmployee();
    }
      ngOnInit() {
      }
   }

and later at the html:然后在 html 中:

 <form #employeeform="ngForm" (ngSubmit)="onSubmit(employeeform)">
          <input type="hidden" name="_id"  [(ngModel)]="employee._id" #_id="ngModel"/>
        </form>

Or pass it again with Injection.或者用 Injection 再传一遍。 At the moment, the problem is that your EmployeeComponent can't target like you want (passing from html to the service variable), so you are getting - Undefined error.目前,问题是您的 EmployeeComponent 不能像您想要的那样定位(从 html 传递到服务变量),所以您得到 -未定义错误。

Initially, when the component is loaded, the employee.service has no value set for selectedEmployee .最初,当加载组件时, employee.service没有为selectedEmployee设置值。 The html is rendered and the [(ngModel)]="employeeservice.selectedEmployee._id" expects a value of employeeservice.selectedEmployee._id .呈现 html 并且[(ngModel)]="employeeservice.selectedEmployee._id"期望值为employeeservice.selectedEmployee._id But employeeservice.selectedEmployee is not initialized yet, hence the error.但是employeeservice.selectedEmployee尚未初始化,因此出现错误。

I would suggest you to use a default _id in case you haven't set the employeeservice.selectedEmployee._id .如果您没有设置employeeservice.selectedEmployee._id ,我建议您使用默认的 _id 。

For that use [(ngModel)]="employeeservice.selectedEmployee? employeeservice.selectedEmployee._id: 0"为此使用[(ngModel)]="employeeservice.selectedEmployee? employeeservice.selectedEmployee._id: 0"

It is as the error says: you want to access the _id but the selectedEmployee is never actually defined.正如错误所说:您想访问 _id 但selectedEmployee从未真正定义过。

You can either only display the element when it has been defined using *ngIf on your html element or give it a default value like so selectedEmployee: Employee = {} (setting any variable needed from the class accordingly)您可以仅在 html 元素上使用*ngIf定义该元素时才显示该元素,或者为其提供默认值,例如selectedEmployee: Employee = {} (相应地设置类所需的任何变量)

Your employee.service.ts file should be like this.您的 employee.service.ts 文件应该是这样的。

 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';
 import { Observable } from 'rxjs';
 import { Employee } from './employee.model';

 @Injectable({
   providedIn: 'root'
 })
 export class EmployeeService {
     selectedEmployee: Employee = {    
    _id: '',
    name: '',
    position: '',
    office: '',
    salary: null
  };
   employees: Employee[];

   constructor() { }
 }

暂无
暂无

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

相关问题 无法在ngOnInit()Angular7上读取未定义的属性“id” - Cannot read property 'id' of undefined on ngOnInit() Angular7 Angular TypeError:无法读取未定义的属性“id” - Angular TypeError: Cannot read property 'id' of undefined IONIC 4 + Angular7:错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ then” - IONIC 4 + Angular7: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'then' of undefined 如何修复angular7中的“无法读取未定义的属性”错误”? - How to fix 'Cannot read property 'errors' of undefined' in angular7? Angular7 FullCalendar错误:无法读取未定义的属性“ length” - Angular7 FullCalendar error: Cannot read property 'length' of undefined 错误TypeError:无法读取未定义的属性“ id”(角度) - ERROR TypeError: Cannot read property 'id' of undefined (Angular) TypeError:无法读取编辑视图模板上未定义的属性“ Id”-Angular 2 - TypeError: Cannot read property 'Id' of undefined on edit view template - Angular 2 给出TypeError的角度:“无法读取未定义的属性&#39;id&#39;” - Angular giving TypeError: “Cannot read property 'id' of undefined” Angular ActivateRoute参数TypeError:无法读取未定义的属性“ id” - angular activatedRoute params TypeError: Cannot read property 'id' of undefined TypeError:无法读取未定义的属性&#39;id&#39;-Angular 8 Testing - TypeError: cannot read property 'id' of undefined - Angular 8 Testing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM