2016-08-16 190 views
2

,我发现了以下错误:Uncaught TypeError: result.subscribe is not a function遗漏的类型错误:result.subscribe不是一个函数

这里也是错误的截图:

enter image description here

但我试图抓住错误。在下面你可以看到我的代码。

login.component.ts:

import { Component } from '@angular/core'; 
import { UserService } from '../../services/user.service'; 
import { User } from '../../models/user'; 
import {ToasterContainerComponent, ToasterService, ToasterConfig} from 'angular2-toaster/angular2-toaster'; 

@Component({ 
    moduleId: module.id, 
    selector: 'login', 
    directives: [ToasterContainerComponent], 
    templateUrl: 'login.component.html', 
    providers: [UserService, ToasterService] 
}) 

export class LoginComponent { 
    user: User = new User(); 
    loginRes: String; 
    private toasterService: ToasterService; 

    public toasterconfig: ToasterConfig = new ToasterConfig({ 
     showCloseButton: true, 
     tapToDismiss: false, 
     timeout: 0 
    }); 

    constructor(private _userService: UserService, toasterService: ToasterService) { 
     this.toasterService = toasterService; 
    } 

    data = {}; 
    onSubmit() { 
     this._userService.login(this.user) 
      .subscribe(
       res => { 
        console.log("res onSubmit"); 
        console.log(res); 
       }, 
       function(error) { console.log("Error happened" + error)} 
      ); 
    } 
} 

user.service.ts:

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

@Injectable() 
export class UserService { 
    private loginUrl: string; 

    constructor(private _http: Http) { 

    } 

    login(user: User) { 
     this.loginUrl = "http://localhost:3000/api/auth/login"; 
     let data = { "username": user.username, "password": user.password }; 
     let body = JSON.stringify(data); 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers }); 

     return this._http.post(this.loginUrl, body, options) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

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

    private handleError(error: any) { 
     console.log('Yup an error occurred', error); 
     return error.message || error; 
    } 
} 

正如你可以看到我已经试图抓住在login()方法的错误user.service.ts。任何人都知道我可以如何解决这个问题?

+0

你可以添加屏幕截图吗?直接回答你的问题,而不是外部链接。请在堆栈轨迹可见的地方添加一个(底部节点展开)。 –

+0

@GünterZöchbauer完成:) – superkytoz

+0

这绝对是更好的,但我不知道是什么原因导致此错误: - / –

回答

8

handleError()功能需要。如果你看一下HTTP Client Angular 2 docs有一个例子返回一个Observable

,但对于您的具体情况

更换

private handleError(error: any) { 
    console.log('Yup an error occurred', error); 
    return error.message || error; 
} 

private handleError(error: any) { 
    console.log('Yup an error occurred', error); 
    return Observable.throw(error.message || error); 
} 
相关问题