当前位置: 代码迷 >> JavaScript >> 如何正确地将函数从 component.ts 移动到服务文件?
  详细解决方案

如何正确地将函数从 component.ts 移动到服务文件?

热度:92   发布时间:2023-06-03 18:10:57.0

我在我的 component.ts 中编写了一个发送 PUT 请求的函数。 它可以正常工作,但我想将该功能移至 service.ts 文件。 我移动了它,但它不起作用。 当我单击“保存”时,它在控制台中显示错误:

FormsComponent.html:32 错误类型错误:_co.editForm 不是 Object.eval [as handleEvent] (FormsComponent.html:32) at handleEvent (core.js:23008) at callWithDebugContext (core.js:24078) at Object 中的函数.debugHandleEvent [as handleEvent] (core.js:23805) at dispatchEvent (core.js:20457) at core.js:20904 at HTMLButtonElement。 (platform-b??rowser.js:993) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423) at Object.onInvokeTask (core.js:17279) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422) View_FormsComponent_0 @FormsComponent.html:32 proxyClass @compiler.js:18234 push../node_modules/@angular /core/fesm5/core.js.DebugContext_.logError @ core.js:24040 push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:15761 dispatchEvent @core.js: 20461(匿名)@core.js:20904(匿名)@platform-b??rowser.js:993 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:423 onInvokeTask @ core. js:17279 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:422 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone. js:195 push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:498 invokeTask @ zone.js:1744 globalZoneAwareCallback @ zone.js:1770 FormsComponent.html:32 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 31, nodeDef: {…}, elDef: {…}, elView: {…}}

这是我的 forms.component.ts 文件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormService } from './forms.service';
import { form } from './form-interface';
import { HttpClient } from '@angular/common/http';

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


export class FormsComponent implements OnInit {

  formsUrl = "https://jsonplaceholder.typicode.com/posts";
  id: any;
  form: form = {
    id: 0,
    userId: 0,
    title: '',
    body: ''
  };

  constructor(private formService: FormService ,private route: ActivatedRoute,
    private router: Router, private http: HttpClient) { }

  ngOnInit() {
    this.id=this.route.snapshot.params['id'];

    this.formService.getForms(this.id).subscribe(
      (forms: any) => {
        this.form = forms[0];
        console.log(this.form);
      }
    );

  }

  deleteForm() {
    this.http.delete(this.formsUrl + "/" + this.form.id)
    .subscribe(
      data  => {
      console.log("DELETE Request is successful ", data);
      },
      error  => {
      console.log("Error", error);
      }
    );
  }

}

这是我的 forms.service.ts 文件:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { form } from './form-interface';



@Injectable({
    providedIn: 'root'
}) 

export class FormService {

formsUrl = "https://jsonplaceholder.typicode.com/posts";
form: form = {
    id: 0,
    userId: 0,
    title: '',
    body: ''
  };


    constructor(private http: HttpClient) { }

    getForms(id) {
        return this.http.get('https://jsonplaceholder.typicode.com/posts'
        + "?id=" + id)
      }

      editForm() {
        fetch(this.formsUrl + "/" + this.form.id, {
          method: 'PUT',
          body: JSON.stringify(this.form),
          headers: {
            "Content-type": "application/json; charset=UTF-8"
          }
        })
        .then(response => response.json())
        .then(json => console.log(json));
      }


}

这是我的 HTML 文件:

<div class="forms container">
  <form #postForm="ngForm">
      <div class="form-group">
          <label for="title">Title</label>
          <input [(ngModel)]="form.title"
          name="title"  
          id="title" 
          type="text" 
          class="form-control"
          >
      </div>
      <div class="form-group">
        <label for="body">Body</label>
        <textarea [(ngModel)]="form.body" 
        name= "body" 
        id="body" 
        cols="30" 
        rows="10" 
        class="form-control"
        ></textarea>
      </div>
      <button class="btn btn-success" (click) = editForm()>Save</button>
      <button class="btn btn-danger pull-right" (click) = deleteForm()>Delete</button>
  </form>
</div>

您不能在模板中调用editForm() ,因为它不存在于您的组件中。 如果要从服务调用该函数,请改用formService.editForm()

但在这种情况下,您需要将formService公开,因此请使用public formService: FormService而不是private formService: FormService

您还可以在组件中克隆该函数,这样您就不需要更改模板并使服务公开,如public editForm = formService.editForm

或者

editForm() {
     return this.formService.editForm();
}

似乎解析错误。 尝试修复 html 中的错误:

put (click) = "editForm()" and (click) = "deleteForm()"

<div class="forms container">
  <form #postForm="ngForm">
      <div class="form-group">
          <label for="title">Title</label>
          <input [(ngModel)]="form.title"
          name="title"  
          id="title" 
          type="text" 
          class="form-control"
          >
      </div>
      <div class="form-group">
        <label for="body">Body</label>
        <textarea [(ngModel)]="form.body" 
        name= "body" 
        id="body" 
        cols="30" 
        rows="10" 
        class="form-control"
        ></textarea>
      </div>
      <button class="btn btn-success" (click) = "editForm()">Save</button>
      <button class="btn btn-danger pull-right" (click) = "deleteForm()">Delete</button>
  </form>
</div>

如果你想保持干净整洁,你可以这样做:

export class FormsComponent implements OnInit {
  form = this.formService.form;

  constructor(private formService: FormService, private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    this.id = this.route.snapshot.params['id'];

    this.formService.loadFormsById(this.id)
        .subscribe(([form]) => this.formService.updateForm(form));
  }

  saveForm() {
    this.formService.saveForm();
  }

  deleteForm() {
    this.formService.deleteForm();
  }

}

和服务:

export class FormService {

    formsUrl = "https://jsonplaceholder.typicode.com/posts";
    form: form = {
       id: 0,
       userId: 0,
       title: '',
       body: ''
    };


    constructor(private http: HttpClient) { }

    loadFormsById(id) {
       // load your form here
    }

    updateForm(form) {
       // update your form here
    }

    saveForm() {
       // save your form here
    }

    deleteForm() {
       // delete your form here
    }
}
  相关解决方案