简体   繁体   English

我该如何解决 - “订阅”类型上不存在“那么”属性

[英]How can I solve - Property 'then' does not exist on type 'Subscription'

I wrote PUT and DELETE methods inside their functions ("editForm" and "deleteForm" respectively).我在它们的函数中编写了 PUT 和 DELETE 方法(分别是“editForm”和“deleteForm”)。

I wanted to display setAlert() function after each request successfully completes.我想在每个请求成功完成后显示setAlert()函数。 therefore, I used .then() method and it works perfectly inside editForm function as you can see it below.因此,我使用了.then()方法,它在editForm函数中完美运行,如下所示。

but when I do the same for deleteForm , .then() method does not works, because it says: " Property 'then' does not exist on type 'Subscription' ".但是当我对deleteForm做同样的deleteFormdeleteForm .then()方法不起作用,因为它说:“属性 'then' 在类型 'Subscription' 上不存在”。 So how can I solve this?那么我该如何解决这个问题呢?

Here is my component.ts file:这是我的 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';
import { alert } from './alert';

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


export class FormsComponent implements OnInit {

  alert: alert;
  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.alert = new alert();

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

  editPost() {
    this.formService.editForm().then((res:any) => {
      this.formService.alert.setAlert("Post has been successfully saved !");
    })
  }

  deletePost() {
    this.formService.deleteForm().subscribe(
      data  => {
        console.log("DELETE Request is successful ", data);
      },
      error  => {
        console.log("Error", error);
      }
    ).then(() => {
      this.formService.alert.setAlert("Post has been successfully deleted !");
    })
  }

}

Here is my service.ts file:这是我的 service.ts 文件:

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


@Injectable({
    providedIn: 'root'
}) 

export class FormService {

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


    constructor(private http: HttpClient) { 
      this.alert = new alert();
    }

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

    editForm() {
        return 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())
    }

    deleteForm() {
        return this.http.delete(this.formsUrl + "/" + this.form.id);
      }

}

because http returns observable not promise.因为 http 返回 observable 而不是 promise。 Use .subscribe here.It will solve your problem在此处使用 .subscribe。它将解决您的问题

The editform method uses JavaScript fetch api to call the service, which returns the promise so then method works there. editform方法使用 JavaScript fetch api 调用服务,该服务返回承诺, then方法在那里工作。 In deleteForm method, you are making a service call using angular HttpClient which returns observable.deleteForm方法中,您正在使用返回 observable 的deleteForm HttpClient进行服务调用。 instead of using then you should use subscribe method而不是使用then你应该使用subscribe方法

deleteForm() {
        return this.http.delete(this.formsUrl + "/" + this.form.id);
}

In your component.ts在你的 component.ts

 deletePost() {
    this.formService.deleteForm().subscribe(
      data  => {
        console.log("DELETE Request is successful ", data);
        this.formService.alert.setAlert("Post has been successfully deleted !");
      },
      error  => {
        console.log("Error", error);
      }
    )
  }

You can use message when you get a proper response while you get the response in subscribe method and call alert into it Like below当您在订阅方法中获得响应并调用警报时,您可以在获得正确响应时使用消息,如下所示

deletePost() {
this.formService.deleteForm().subscribe(
  data  => {
    console.log("DELETE Request is successful ", data);
    this.formService.alert.setAlert("Post has been successfully deleted !");
  },
  error  => {
    console.log("Error", error);
  }
))

} }

暂无
暂无

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

相关问题 我该如何解决“属性&#39;样式&#39;不存在类型&#39;元素&#39;错误? - How can i solve a "Property 'style' does not exist on type 'Element' error? 我该如何解决“'元素'类型上不存在属性'checkValidity'。” ts(2339) 错误 - How can i solve a "Property 'checkValidity' does not exist on type 'Element'." ts(2339) error 如何解决类型“从不”中不存在的属性 - How to solve Property does not exist in type 'never' 属性“ do”在“订阅”类型上不存在 - Property 'do' does not exist on type 'Subscription' 如何解决“IntrinsicAttributes &amp; Function”类型上不存在的类型属性“”? - How to solve Type Property '' does not exist on type 'IntrinsicAttributes & Function'? 如何解决&#39;属性&#39;宽度&#39;在类型&#39;HTMLElement&#39;上不存在。&#39; 当使用// @ ts-check在vscode中键入检查Javascript(NOT Typescript)时? - How do I solve 'Property 'width' does not exist on type 'HTMLElement'.' when type checking Javascript (NOT Typescript) using // @ts-check in vscode? 我该如何克服错误:“选择”类型上不存在“节点”属性 <string[]> “? - How can I overcome the error: Property 'nodes' does not exist on type 'Selection<string[]>'? 解决打字稿错误的最佳方法 - 类型上不存在属性 - Best way to solve typescript error - property does not exist on type 如何解决 Angular 订阅错误? 类型“AngularFireList”上不存在属性“订阅”<unknown> &#39;.ts(2339) - How to solve Angular subscribe error? Property 'subscribe' does not exist on type 'AngularFireList<unknown>'.ts(2339) 在Angular 7中的调试过程中,如何解决“类型&#39;{}&#39;上不存在属性&#39;NRO_LIQUIDACION&#39;。”的问题 - How to solve the issue “ Property 'NRO_LIQUIDACION' does not exist on type '{}'.” on the debuging procces in Angular 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM