使用Angular2 RxJS时遇到困难

时间:2017-02-27 22:28:32

标签: angular webpack rxjs angular-cli

我正在尝试构建一个简单的服务来检索一些数据:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import {UtilsService} from "./../../util/util.service";
import {LoginResult} from "./LoginResult";

@Injectable()
export class LoginService {
  private url:string = this.utilsService.getBaseRestUrl() + "ad/authentication-service/login";

  constructor(private http:Http, private utilsService:UtilsService) {
  }

  login(user:Object):Observable<LoginResult> {
    return this.http
      .get(this.url)
      .map(response => response.json().data as LoginResult);
  }
}

但是我不能让事情发生,因为这个导入:import 'rxjs/operator/map';似乎没有得到解决。我使用IntelliJ并获得unresolved function or method error

当我尝试运行Web控制台时写道:ReferenceError: LoginService is not defined - 显然是因为这个未解决的功能。

当我导航到node_modules时,我可以找到包含所需功能的map.js。我使用Angular cli所以我没有任何系统JS配置&#39;因为Angular Cli基于Webpack。

如何告诉Webpack定义函数的位置?或者我做错了什么?

2 个答案:

答案 0 :(得分:1)

我使用了angular-cli并生成了我的应用程序,它按预期工作。

请尝试以下操作,如果有效,请告诉我。

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';

import {Observable} from 'rxjs';//Removed:/Observable
//import 'rxjs/add/operator/map';

import {UtilsService} from "./../../util/util.service";
import {LoginResult} from "./LoginResult";

@Injectable()
export class LoginService {
  private url:string = this.utilsService.getBaseRestUrl() + "ad/authentication-service/login";

  constructor(private http:Http, private utilsService:UtilsService) {
  }

  login(user:Object):Observable<LoginResult> {
    return this.http
      .get(this.url)
      .map((r: Response) => r.json() as LoginResult);
  }
}

以下是您可以使用的示例服务, https://github.com/reflexdemon/shop/blob/master/src/app/user.service.ts

请随意使用为学习angular2而创建的代码。

https://github.com/reflexdemon/shop

答案 1 :(得分:0)

我解决了问题 - 这是解决方案:

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

import {Observable} from 'rxjs';

import {LoginResult} from './login.result';
import {UtilsService} from './../../util/util.service'

@Injectable()
export class LoginService {
  private url:string;

  constructor(private http: Http, utilsService: UtilsService) {
    this.url = utilsService.getBaseRestUrl() + "ad/authentication-service/login";
  }

  login(user:Object):Observable<LoginResult> {
    return this.http.post(this.url, user)
      .map((r: Response) => r.json() as LoginResult)
      .catch(LoginService.handleError);
  }

  private static handleError(error: any): Observable<any> {
    console.log('An error occurred', error); // for demo purposes only
    return Observable.throw(error.json().message || 'Server error');
  }
}

问题在于使用其他服务:

private url:string = this.utilsService.getBaseRestUrl()

utilsService显然未定义,因此我将其移至构造函数并将服务添加到Components providers数组中:providers: [LoginService, UtilsService]

应用程序启动时没有错误。