【问题标题】:Getting error when subscribing to promise订阅承诺时出错
【发布时间】:2016-04-19 07:15:39
【问题描述】:

页面加载时出现错误提示

people.ts?9320:22 SyntaxError: Unexpected token 
<(…)PeopleComponent.apiService.people.subscribe.error @ people.ts?
9320:22SafeSubscriber.__tryOrUnsub @ VM38600:166SafeSubscriber.error @ 
VM38600:127Subscriber._error @ VM38600:77Subscriber.error @ 
VM38600:57MapSubscriber._next @ VM38955:51Subscriber.next @ 
VM38600:51onLoad @ VM38808:57ZoneDelegate.invokeTask @ 
VM38526:423NgZoneImpl.inner.inner.fork.onInvokeTask @ 
VM38628:36ZoneDelegate.invokeTask @ VM38526:422Zone.runTask @ 
VM38526:320ZoneTask.invoke @ VM38526:490

这是我的代码:

export class PeopleComponent {
    people: any;
    constructor(apiService: Api) {
        apiService.people
            .subscribe({
                next: x => (this.people = x),
                error: e => console.error(e), //error line 22 is here!
                complete: () => console.log('Completed!')
            });
    }
}

我的 API 服务:

import {Injectable} from 'angular2/core';
import { Http } from 'angular2/http';

@Injectable()
export class Api {
  people: any;

  constructor(http: Http) {
    this.people = http.get(require('./people.json'))
      .map(response => response.json());
  }
}

有什么想法吗?

【问题讨论】:

  • 您是否包含&lt;script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"&gt;&lt;/script&gt;
  • @GünterZöchbauer 它包含在 webpack 中
  • 看起来像stackoverflow.com/…之一

标签: angular rxjs5


【解决方案1】:

您可以尝试这样订阅:

apiService.people
      .subscribe(
        x => {this.people = x;},
        e => {console.error(e);},
        () => {console.log('Completed!');}
      });

请参阅此文档:

【讨论】:

  • 还有什么想法吗?
  • 你能告诉我更多关于你在你的项目中使用的东西吗?你使用 TypeScript 还是 ES6?如果使用 TypeScript,你如何编译你的代码?谢谢!
  • 我正在使用 TypeScript
  • 我刚刚看到您在服务级别使用require。似乎很奇怪。你应该使用这个:plnkr.co/edit/ESkRoqXt2fmnFdCjiDzp?p=preview.
  • 是的,我可能对给出错误的那个有问题。这是我目前正在探索的
猜你喜欢
  • 2019-08-31
  • 2017-09-21
  • 2017-07-29
  • 2016-06-26
  • 2017-12-12
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多