如何将功能从component.ts正确移动到服务文件?

时间:2019-02-21 09:30:15

标签: javascript angular typescript

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

  

FormsComponent.html:32错误TypeError:_co.editForm不是函数       在Object.eval [作为handleEvent](FormsComponent.html:32)       在handleEvent(core.js:23008)       在callWithDebugContext(core.js:24078)       在Object.debugHandleEvent [作为handleEvent](core.js:23805)       在dispatchEvent(core.js:20457)       在core.js:20904       在HTMLButtonElement。 (platform-b​​rowser.js:993)       在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask   (zone.js:423)       在Object.onInvokeTask(core.js:17279)       在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错误上下文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>

3 个答案:

答案 0 :(得分:0)

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

但是在那种情况下,您需要公开formService,所以使用public formService: FormService而不是private formService: FormService

您还可以在组件中克隆该功能,因此无需更改模板并将服务公开,例如public editForm = formService.editForm

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

答案 1 :(得分:0)

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

输入(click)=“ editForm()”和(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>

答案 2 :(得分:0)

如果要保持整洁,可以执行以下操作:

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
    }
}