【问题标题】:Angular 2: Property 'suscribe' does not exist on type 'Observable<Response>'Angular 2:“Observable<Response>”类型上不存在属性“订阅”
【发布时间】:2018-02-01 14:54:48
【问题描述】:

上面的错误是我在“编译”后在命令行中得到的(指 post 请求中 subscribe 方法的第二次调用。非常简单),我订阅了一个 observable 以获得对http 请求。没有服务(至少是我创建的)被导入到其他文件夹中,据说 post 方法工作所需的一切。此外,我还设置了模拟 API,邮递员可以成功地向/从该 API 发出 get 和 post 请求。

import { Component, OnInit } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';

@Component({
    selector: 'simple-http',
    templateUrl: 'simple-http.component.html'
})

export class SimpleHttpComponent implements OnInit{
    data: Object;


    loading: boolean;

    constructor(public http: Http) {
    }



    ngOnInit() {

    }

    getUser(): Object {
        this.loading = true;
        this.http.get('http://demo1495487.mockable.io/cort')
            .subscribe((res: Response) => {
                this.data = res.json();
                this.loading = false;
                console.log(this.data);
            });
            return this.data;
    }

    addUser(): void {
      this.loading = true;
      this.http.post('http://greenmachine.mockable.io/cortfield',
      JSON.stringify({
        body: 'bar',
        title: 'foo',
        userId: 1
      }))
      .suscribe((res: Response) => {
        this.data = res.json();
        console.log(this.data);
        this.loading = false;
      });
    }





}

【问题讨论】:

  • 不订阅就是订阅

标签: angular rest web-services http typescript


【解决方案1】:

当我查看您的代码时,我可以理解您的代码拼写错误。

更改您的代码
 .suscribe((res: Response) => {
        this.data = res.json();
        console.log(this.data);
        this.loading = false;
      });

.subscribe((res: Response) => {
            this.data = res.json();
            console.log(this.data);
            this.loading = false;
          });

在订阅之前尝试映射到 JSON。

  this.http.post('http://greenmachine.mockable.io/cortfield',
        JSON.stringify({
          body: 'bar',
          title: 'foo',
          userId: 1
        })).map((response: Response) => {
            return <any>response.json();
        }).subscribe((response: any) => {

            this.data = response;
            console.log(this.data);
            this.loading = false;
        });

this.http.post('http://greenmachine.mockable.io/cortfield',
            JSON.stringify({
              body: 'bar',
              title: 'foo',
              userId: 1
            })).subscribe(result => this.data=result.json());

【讨论】:

  • 该错误已更正,仍然出现相同的错误。
  • @PaulHubert 我已经更新了我的答案..你能试试吗
  • @PaulHubert 我认为第二个实现与您的实现相同,但有一个小的变化。请尝试一下
猜你喜欢
  • 2016-12-01
  • 2016-08-25
  • 1970-01-01
  • 2018-11-30
  • 2016-10-31
  • 2016-09-09
  • 1970-01-01
相关资源
最近更新 更多