【问题标题】:Property 'subscribe' does not exist on type 'Observable<User> | Error'. Property 'subscribe' does not exist on type 'Error'类型 'Observable<User> 上不存在属性 'subscribe' |错误'。 “错误”类型上不存在属性“订阅”
【发布时间】:2018-01-29 05:36:45
【问题描述】:

我一直在尝试从我的登录服务返回订阅:

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {User} from '../models/user';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class LoginService {
    constructor(private http: Http) { }

    login(username: string, password: string){
      if(username && password){
        return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
          .map((response: Response) =>  response.json().data as User);
      }
      else { 
        return new Error('Credentials not provided');
      }
}

并在我的组件中调用它:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { LoginService } from './login.service';

@Component({
  moduleId: module.id,
  templateUrl: 'login.component.html',
  providers: [LoginService]
})

export class LoginComponent implements OnInit {
  model: any = {};
  loading = false;
  returnUrl: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private loginService: LoginService) { }

  ngOnInit() {
    // reset login status
    //this.loginService.logout();

    // get return url from route parameters or default to '/'
    //this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  }

  login() {
    this.loading = true;
    console.log(this.loginService.login(this.model.username, this.model.password));


    /*  .subscribe(
         data => {
             this.router.navigate([this.returnUrl]);
         },
         error => {
             console.log(error);
             this.loading = false;
         }); */
  }
}

但是在打印 observable 时我得到了这个:

Observable {_isScalar: false, source: Observable, operator: 
MapOperator}operator: MapOperator {thisArg: undefined, project: ƒ}source: 
Observable_isScalar: false_subscribe: ƒ (responseObserver)arguments: 
(...)caller: (...)length: 1name: ""prototype: {constructor: ƒ}__proto__: ƒ 
()[[FunctionLocation]]: http.es5.js:1187[[Scopes]]: Scopes[3]__proto__: 
Object_isScalar: false__proto__: catch: ƒ _catch(selector)forEach: ƒ (next, 
PromiseCtor)lift: ƒ (operator)map: ƒ map(project, thisArg)subscribe: ƒ 
(observerOrNext, error, complete)toPromise: ƒ 
toPromise(PromiseCtor)Symbol(observable): ƒ ()_catch: ƒ 
_catch(selector)_subscribe: ƒ (subscriber)_trySubscribe: ƒ 
(sink)constructor: ƒ Observable(subscribe)__proto__: Object

在顶级观察者对象中似乎没有订阅属性,但在私有原型对象中。我已经尝试了其他答案中提供的所有解决方案。只是不工作:(

这是我的 json 包:

{
  "name": "pd-free-angularcli",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@ngui/map": "^0.18.3",
    "@types/googlemaps": "^3.26.14",
    "arrive": "^2.3.1",
    "bootstrap": "^3.3.5",
    "bootstrap-notify": "^3.1.3",
    "chartist": "^0.9.4",
    "core-js": "^2.4.1",
    "jquery": "^1.12.4",
    "moment": "^2.18.1",
    "proxy-polyfill": "^0.1.7",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.1",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

【问题讨论】:

  • 我尝试返回任何类型的 observbale,导入了所有必需的运算符,但似乎不起作用
  • 您正在从 login 函数返回一个 Error。我想你可能会遇到错误分支。

标签: angular rxjs observable


【解决方案1】:

我不确定你是否删减了什么,但这看起来你正在订阅console.log

console.log(this.loginService.login(this.model.username, this.model.password));

/*  .subscribe(
     data => {

所以我猜你已经剪掉了一些东西,你的问题就在这里:

else { 
    return new Error('Credentials not provided');
}

您正在返回一个错误。不是可观察的。这应该可以解决它:

return Observable.throw(new Error('Credentials not provided'));

【讨论】:

    【解决方案2】:
    import { Injectable } from '@angular/core';
    import { Http, Headers, Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import {User} from '../models/user';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/map';
    
    @Injectable()
    export class LoginService {
        constructor(private http: Http) { }
    
        login(username: string, password: string){
          if(username && password){
            return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
              .map((response: Response) =>  response.json().data as User);
          }
          else { 
            return Observable.throw(new Error('Credentials not provided')); <---------
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 2019-12-26
      • 2020-11-01
      • 2018-07-30
      • 2019-01-03
      • 2020-12-01
      • 1970-01-01
      相关资源
      最近更新 更多