属性Observable上不存在属性'then'

时间:2022-10-01 23:00:08

I'm new to angular 2 and I'm trying to make a REST GET request, but I'm getting this error when trying:

我是angular 2的新手,我正在尝试发出一个REST GET请求,但是在尝试时遇到了这个错误:

error TS2339: Property 'then' does not exist on type 'Observable<Connection[]>'.

Here is the component calling the service:

以下是调用服务的组件:

import { Component, OnInit} from '@angular/core';
import { Router }           from '@angular/router';

import { Connection }       from './connection';
import { ConnectionService }      from './connection.service';

let $: any = require('../scripts/jquery-2.2.3.min.js');

@Component({
  selector: 'connections',
  styleUrls: [ 'connections.component.css' ],
  templateUrl: 'connections.component.html',
  providers: [ConnectionService]
})

export class ConnectionsComponent implements OnInit {

  connections: Connection[];
  selectedConnection: Connection;

  constructor(
    private connectionService: ConnectionService,
    private router: Router) { }

  getConnections(): void {
    this.connectionService.getConnections().then(connections => {
      this.connections = connections;
    });
  }

  ngOnInit(): void {
    this.getConnections();
  }

  onSelect(connection: Connection): void {
    this.selectedConnection = connection;
  }

  gotoDetail(): void {
    this.router.navigate(['/connectiondetail', this.selectedConnection.id]);
  }
}

Here is the ConnectionService:

这是ConnectionService:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Connection }     from './connection';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class ConnectionService {

  private connectionsUrl = 'https://localhost/api/connections';  // URL to web API

  constructor (private http: Http) {}

  getConnections(): Observable<Connection[]> {
    return this.http.get(this.connectionsUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure

    let errMsg: string;

    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);

    return Observable.throw(errMsg);
  }
}

How do I fix this error?

我该如何解决这个错误?

Thank you,

谢谢,

Tom

汤姆

1 个解决方案

#1


9  

An Observable doesn't have a promise-like method as then. In your service you are performing an http call which returns an Observable and you map this Observable to another Observable.

Observable当时没有类似承诺的方法。在您的服务中,您正在执行一个http调用,该调用返回一个Observable并将此Observable映射到另一个Observable。

If you really want to use the promise-style API, you need to convert your Observable to a promise using the toPromise operator. This operator is not available by default so that you also need to import it once in your project.

如果您真的想使用promise样式的API,则需要使用toPromise运算符将Observable转换为promise。默认情况下,此运算符不可用,因此您还需要在项目中导入一次。

import 'rxjs/add/operator/toPromise';

Using promises is okay, but there are some good reasons to use the Observable APIs directly. For details, please see this blog post advertising the usage of Observables.

使用promises是可以的,但有一些很好的理由直接使用Observable API。有关详细信息,请参阅此博客文章,宣传Observables的用法。

If you want to use the Observable API directly then replace your then call with a subscribe call. But remember that every subscription also needs to be cancelled when your component gets destroyed.

如果要直接使用Observable API,请使用订阅调用替换您的then调用。但请记住,当组件被销毁时,每个订阅也需要被取消。

getConnections(): void {
  this.subscription = this.connectionService.getConnections()
    .subscribe(connections => this.connections = connections);
}

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

Another option when working with Observables is to assign the resulting Observable to a field in your component and then use the async pipe. Doing so, Angular will handle the subscriptions for you.

使用Observables时的另一个选择是将结果Observable分配给组件中的字段,然后使用异步管道。这样做,Angular将为您处理订阅。

#1


9  

An Observable doesn't have a promise-like method as then. In your service you are performing an http call which returns an Observable and you map this Observable to another Observable.

Observable当时没有类似承诺的方法。在您的服务中,您正在执行一个http调用,该调用返回一个Observable并将此Observable映射到另一个Observable。

If you really want to use the promise-style API, you need to convert your Observable to a promise using the toPromise operator. This operator is not available by default so that you also need to import it once in your project.

如果您真的想使用promise样式的API,则需要使用toPromise运算符将Observable转换为promise。默认情况下,此运算符不可用,因此您还需要在项目中导入一次。

import 'rxjs/add/operator/toPromise';

Using promises is okay, but there are some good reasons to use the Observable APIs directly. For details, please see this blog post advertising the usage of Observables.

使用promises是可以的,但有一些很好的理由直接使用Observable API。有关详细信息,请参阅此博客文章,宣传Observables的用法。

If you want to use the Observable API directly then replace your then call with a subscribe call. But remember that every subscription also needs to be cancelled when your component gets destroyed.

如果要直接使用Observable API,请使用订阅调用替换您的then调用。但请记住,当组件被销毁时,每个订阅也需要被取消。

getConnections(): void {
  this.subscription = this.connectionService.getConnections()
    .subscribe(connections => this.connections = connections);
}

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

Another option when working with Observables is to assign the resulting Observable to a field in your component and then use the async pipe. Doing so, Angular will handle the subscriptions for you.

使用Observables时的另一个选择是将结果Observable分配给组件中的字段,然后使用异步管道。这样做,Angular将为您处理订阅。