首页 > 解决方案 > 如何处理将所有功能移至一项服务的副作用?

问题描述

我在我的service.ts. 所有功能都可以正常工作,但是将所有这些功能移到一个服务中后,出现了一个问题。当我打开add-form.component有一个空的输入字段用于通过 POST 请求添加内容时,这些字段在打开时第一次是空的,但是当我返回“帖子”部分时,单击“编辑”按钮以查看任何帖子(forms.component,我有相同的输入字段,但它们填充了相关数据)然后返回add-form.component,它填充了我最近通过帖子部分打开的数据。我知道很难阅读我对问题的描述,因此您可以在 github 上查看我的项目:https ://github.com/lashamerebashvili/todolistapp/tree/posts

表单-add.component.ts:

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

@Component({
  selector: 'app-form-add',
  templateUrl: './form-add.component.html',
  styleUrls: ['./form-add.component.css']
})
export class FormAddComponent implements OnInit {

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

  ngOnInit() {
  }

}

添加-form.component.html:

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

forms.component.ts:

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

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

export class FormsComponent implements OnInit {

  id: any;
  posts: any;

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

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

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

  ngOnDestroy() {
    this.posts.unsubscribe();
  }

}

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: ''
    };
    add: any;

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

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

    addForm() {
        this.add = this.http.post("https://jsonplaceholder.typicode.com/posts",
          this.form)
          .subscribe(
          data  => {
            console.log("POST Request is successful ", data);
          },
          error  => {
            console.log("Error", error);
          }
          );
    }

}

forms.component.html:

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

标签: javascriptangulartypescript

解决方案


推荐阅读