简体   繁体   English

类型“可观察”不存在属性“ toPromise” <Response> &#39;并且参数&#39;response&#39;隐式具有&#39;any&#39;类型

[英]Property 'toPromise' does not exist on type 'Observable<Response>' And Parameter 'response' implicity has an 'any' type

This My .service.ts but I've two errors : 这是我的.service.ts,但是我有两个错误:

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/toPromise';

import { Product } from './Product';

@Injectable()
export class ProductService {

    private headers = new Headers({ 'Content-Type': 'application/json' });
    private productsUrl = 'app/products';  // URL to web api

    constructor(private http: Http) { }

    getProducts(): Promise<Product[]> {
        return this.http.get(this.productsUrl)
            .toPromise() //<--- FIRST
            .then(response => response.json().data as Product[]) //<--- TWO
            .catch(this.handleError);
    }

    getProduct(id: number): Promise<Product> {
        return this.getProducts()
            .then(products => products.find(product => product.id === id));
    }

    delete(id: number): Promise<void> {
        const url = `${this.productsUrl}/${id}`;
        return this.http.delete(url, { headers: this.headers })
            .toPromise()
            .then(() => null)
            .catch(this.handleError);
    }

    create(wording: string): Promise<Product> {
        return this.http
            .post(this.productsUrl, JSON.stringify({ wording: wording  }), { headers: this.headers })
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handleError);
    } 

    createFull(product: Product): Promise<Product> {
        return this.http
            .post(this.productsUrl, JSON.stringify({ product: product }), { headers: this.headers })
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handleError);
    }

    update(product: Product): Promise<Product> {
        const url = `${this.productsUrl}/${product.id}`;
        return this.http
            .put(url, JSON.stringify(product), { headers: this.headers })
            .toPromise()
            .then(() => product)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

First : Property 'toPromise' does not exist on type 'Observable' 首先:属性“ toPromise”在“可观察”类型上不存在

and Two :Parameter 'response' implicity has an 'any' type. 和两个:参数'response'隐式具有'any'类型。

I imports 'toPromise', 'Response' an 'Observable' but it still not working... How can I fix this please ? 我导入了“ toPromise”,“响应”为“可观察”,但仍然无法正常工作...如何解决此问题?

Thanks. 谢谢。

EDIT My systemjs.config.js : 编辑我的systemjs.config.js:

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'lib-npm/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
        app: 'app',
        main: 'app/main.js',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      api : { defaultExtension: 'js' },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
  if (!global.noBootstrap) { bootstrap(); }

    // Bootstrap the `AppModule`(skip the `app/main.ts` that normally does this)
  function bootstrap() {
      console.log('Auto-bootstrapping');

      // Stub out `app/main.ts` so System.import('app') doesn't fail if called in the index.html
      System.set(System.normalizeSync('app/main.ts'), System.newModule({}));

      // bootstrap and launch the app (equivalent to standard main.ts)
      Promise.all([
        System.import('@angular/platform-browser-dynamic'),
        getAppModule()
      ])
      .then(function (imports) {
          var platform = imports[0];
          var app = imports[1];
          platform.platformBrowserDynamic().bootstrapModule(app.AppModule);
      })
      .catch(function (err) { console.error(err); });
  }

    // Import AppModule or make the default AppModule if there isn't one
    // returns a promise for the AppModule
  function getAppModule() {
      if (global.noAppModule) {
          return makeAppModule();
      }
      return System.import('app/app.module').catch(makeAppModule)
  }

  function makeAppModule() {
      console.log('No AppModule; making a bare-bones, default AppModule');

      return Promise.all([
        System.import('@angular/core'),
        System.import('@angular/platform-browser'),
        System.import('app/app.component')
      ])
      .then(function (imports) {

          var core = imports[0];
          var browser = imports[1];
          var appComp = imports[2].AppComponent;

          var AppModule = function () { }

          AppModule.annotations = [
            new core.NgModule({
                imports: [browser.BrowserModule],
                declarations: [appComp],
                bootstrap: [appComp]
            })
          ]
          return { AppModule: AppModule };
      })
  }
})(this);

It could perhaps cause a problem, that you import Observable from rxjs/Rx . rxjs/Rx导入Observable可能会引起问题。 Can you try to import from rxjs/Observable ? 您可以尝试从rxjs/Observable导入吗?

EDIT: 编辑:

Perhaps is this the reason for your problem (a bug in VS): Angular 2 2.0.0-rc.1 Property 'map' does not exist on type 'Observable<Response>' not the same as issue report 也许这是导致您出现问题的原因(VS中的错误): Angular 2 2.0.0-rc.1类型“ Observable <Response>”上不存在属性“ map”,与问题报告不同

To the second error: It looks like you have 第二个错误:看起来像你有

"noImplicitAny": true,

in your tsconfig.json . 在您的tsconfig.json This forces you to give types to everything and it does not use the any -type if non is defined. 这会强制您为所有内容提供类型,并且如果未定义,则不使用any -type。 Ether set noImplicitAny to false or you add a type to the response (any, or Response). 以太将noImplicitAny设置为false或将类型添加到响应(任何或响应)。


Additional note: 附加说明:

Don't use toPromise if not necessary. 如有必要,请勿使用toPromise。 In your case, you could work with observables without any problems: 就您而言,您可以毫无问题地使用可观察对象:

return this.http.get(this.productsUrl)
        .map(response => response.json().data as Product[]);

Now you could simply subscribe to them. 现在您可以简单地订阅它们。

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

相关问题 Angular 6:“Observable”类型上不存在“map”属性<Response> &#39; - Angular 6: Property 'map' does not exist on type 'Observable<Response>' 属性&#39;mergeMap&#39;在类型&#39;Observable上不存在 <any> “ - Property 'mergeMap' does not exist on type 'Observable<any>' &#39;Observable&#39; 类型不存在属性 &#39;catch&#39;<any> &#39; - Property 'catch' does not exist on type 'Observable<any>' “响应”类型上不存在属性“数据” - Property 'data' does not exist on type 'Response' “OperatorFunction”类型上不存在属性“订阅”<response, {}> '</response,> - Property 'subscribe' does not exist on type 'OperatorFunction<Response, {}>' 错误TS2339:类型'Observable <Response>'上不存在属性'map' - error TS2339: Property 'map' does not exist on type 'Observable<Response>' 错误:类型&#39;OperatorFunction &lt;{},{} |属性&#39;subscribe&#39;不存在 可观察的 <any> &gt; - Error: property 'subscribe' does not exist on type 'OperatorFunction<{}, {} | Observable<any>> 这不访问http响应对象:对象类型上不存在该属性 - this does not access http response object:property does not exist on type Object NextJs 中的 axios 响应中的类型“never”.ts(2339) 上不存在属性 - Property does not exist on type 'never'.ts(2339) in axios response in NextJs Observable 类型上不存在属性管道 - Property pipe does not exist on type Observable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM