首页 > 解决方案 > 错误类型错误:无法读取未定义的属性“postFeedback”

问题描述

Angular 和 Node 版本

角 CLI:6.2.9 节点:8.17.0

当我单击发送反馈按钮时,它的抛出错误和堆栈跟踪如下:-

ERROR TypeError: Cannot read property 'postFeedback' of undefined
at FeedbackComponent.push../src/app/feedback/feedback.component.ts.FeedbackComponent.sendFeedback (feedback.component.ts:23)
at Object.eval [as handleEvent] (FeedbackComponent.html:5)
at handleEvent (core.js:10251)
at callWithDebugContext (core.js:11344)
at Object.debugHandleEvent [as handleEvent] (core.js:11047)
at dispatchEvent (core.js:7710)
at core.js:9190
at SafeSubscriber.schedulerFn [as _next] (core.js:3563)

反馈.component.html

<div class="container">
  <div class="row">
    <div class="offset-3"></div>
    <div class="col-md-6">
      <form name="form" #f="ngForm" (ngSubmit)="f.form.valid && sendFeedback()" novalidate class="feedback-form">
        <!-- Name -->
        <div class="form-group">
          <label for="name">First Name</label>
          <input type="text"
                 id="name"
                 class="form-control"
                 name="name"
                 placeholder="Your name"
                 [(ngModel)]="model.name"
                 #name="ngModel"
                 [ngClass]="{ 'is-invalid': f.submitted && name.invalid }"
                 required/>
          <!-- input validation group -->
          <div *ngIf="f.submitted && name.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="name.errors?.required">Field is required</div>
          </div>
        </div>
        <!-- Email -->
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text"
                 id="email"
                 class="form-control"
                 name="email"
                 placeholder="Your email"
                 [(ngModel)]="model.email"
                 #email="ngModel"
                 [ngClass]="{ 'is-invalid': f.submitted && email.invalid }"
                 required email/>
          <!-- input validation group -->
          <div *ngIf="f.submitted && email.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="email.errors?.required">Field is required</div>
            <div *ngIf="email.errors?.email">Field is not a valid email</div>
          </div>
        </div>

        <!-- Feedback -->
        <div class="form-group">
          <label for="feedback">Feedback</label>
          <textarea
            id="feedback"
            class="form-control"
            name="feedback"
            placeholder="Your feedback"
            rows="10"
            [(ngModel)]="model.feedback"
            #feedback="ngModel"
            [ngClass]="{ 'is-invalid': f.submitted && feedback.invalid }"
            required minlength="10">
			    </textarea>
          <!-- input validation group -->
          <div *ngIf="f.submitted && feedback.invalid" class="invalid-input">
            <!-- individual validation errors -->
            <div *ngIf="feedback.errors?.required">Field is required</div>
            <div *ngIf="feedback.errors?.minlength">Field is too small (try 10 characters)</div>
          </div>
        </div>

        <button type="submit" class="btn btn-info pull-right">
          <i class="fa fa-envelope-o"></i>
          <span> Send Feedback</span>
        </button>
      </form>
    </div>
    <div class="offset-3"></div>
  </div>
</div>

反馈.component.ts

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ApiService} from '../shared/api.service';
@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  model: FeedbackViewModel = {
    name: '',
    email: '',
    feedback: ''
  };

  constructor(public apiService: ApiService) {
  }

  ngOnInit() {
  }

  sendFeedback(): void {
    this.apiService.postFeedback(this.model).subscribe(
      res => {
        location.reload();
      },
      err => {
        alert('An error has occurred while sending feedback');
      }
    );
  }

}

export interface FeedbackViewModel {
  name: string;
  email: string;
  feedback: string;
}

服务 api.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {FeedbackViewModel} from '../feedback/feedback.component';


@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private BASE_URL = window['cfgApiBaseUrl'] + '/api';
  public ALL_NOTEBOOKS_URL = `${this.BASE_URL}/notebooks/all`;
  private SEND_FEEDBACK_URL = `${this.BASE_URL}/feedback`;

  constructor(private http: HttpClient) {

  }

  getAllNotebooks(): Observable<Notebook[]> {
    return this.http.get<Notebook[]>(this.ALL_NOTEBOOKS_URL);
  }

  postFeedback(feedback: FeedbackViewModel): Observable<any> {
    return this.http.post(this.SEND_FEEDBACK_URL, feedback);
  }

  postNotebook(notebook: Notebook): Observable<Notebook> {
    return this.http.post<Notebook>(this.SAVE_UPDATE_NOTEBOOK, notebook);
  }

  deleteNotebook(id: string): Observable<any> {
    return this.http.delete(this.DELETE_NOTEBOOK_URL + id);
  }

  getAllNotes(): Observable<Note[]> {
    return this.http.get<Note[]>(this.ALL_NOTES_URL);
  }

  getNotesByNotebook(notebookId: string): Observable<Note[]> {
    return this.http.get<Note[]>(this.NOTES_BY_NOTEBOOK_URL + notebookId);
  }

  saveNote(note: Note): Observable<Note> {
    return this.http.post<Note>(this.SAVE_UPDATE_NOTE_URL, note);
  }

  deleteNote(noteId: string): Observable<any> {
    return this.http.delete(this.DELETE_NOTE_URL + noteId);
  }
}

我试图通过将表单更改为“注册表单”来解决它,但它总是显示相同的 TypeError。

标签: angularjsangular

解决方案


该 Angular 错误日志似乎表明注入的服务是“未定义的”。我的猜测是您的服务在您调用它的方法的时间点没有在提供程序中定义,但如果是这种情况,我预计会有更多基于 DI 的错误。这是在您调用它时未加载的特定组件或模块的提供程序数组中吗?

只是一个猜测,祝你好运,快乐编码!


推荐阅读