gpt4 book ai didi

http - 未捕获的类型错误 : result. 订阅不是函数

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:02 27 4
gpt4 key购买 nike

我收到以下错误:Uncaught TypeError: result.subscribe is not a function

这里还有错误的截图:

enter image description here

但我确实试图捕捉到错误。下面你可以看到我的代码。

登录.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)}
);
}
}

用户服务.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;
}
}

如您所见,我已尝试在 user.service.tslogin() 方法中捕获错误。任何可能知道我怎么做的人解决这个问题?

最佳答案

您的handleError() 函数需要返回一个Observable

如果您查看 HTTP Client Angular 2 docs有一个例子,但针对您的具体情况

替换

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);
}

关于http - 未捕获的类型错误 : result. 订阅不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com