javascript - http.post 在 Angular 2 中不起作用

标签 javascript http angular error-handling

为什么我的 http.post 在 angular 2 中不工作。只是无法弄清楚我错过了什么。

这里是 login.component.ts 文件

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

constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
    private alertService: AlertService
){}

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

login(){
   let errMsg: string;
    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(
            data => {
                console.log('Success');
                //this.router.navigate(['/']);
            },
            error => {
                console.log('Error');
                this.loading = false;
            }
        );
}

这是authentication.service.ts

@Injectable()
export class AuthenticationService{

private baseUrl = '..';

constructor(private http: Http){}

login(username: string, password: string): Observable<Response>{
    let body = JSON.stringify({username: username, password: password});
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers});
    const url = `${this.baseUrl}/api/auth/login`;

    return this.http.post(url, body, options)
        .map(this.extractData)
        .catch(this.handleError);

}

logout(){
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
}

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

private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}

这是路由文件

const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },

   // otherwise redirect to home
   { path: '**', redirectTo: '' }
 ];

 @NgModule({
     imports: [ RouterModule.forRoot(appRoutes) ],
     exports: [ RouterModule ]
 })

 export class AppRoutingMoudle{}

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

import { Injectable } from '@angular/core';
import {Headers, Http, Response,RequestOptions} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()

在您的服务之上导入这些,然后在构造函数中执行

 constructor(private _http:Http) { }

然后你可以用这个._http.post

关于javascript - http.post 在 Angular 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860135/

相关文章:

javascript - 使用纯 js 删除 css 属性失败

javascript - 查找对象的值

http - 使用 SSL 连接时可以看到哪些 http header ?

angular - 如何使用不同 Observable 的值更新 Observable

javascript - 如果没有匹配的内容,则删除元素及其值

javascript - 下载一个文件,片段存储在多个服务器上(HTTP)

c# - 是否可以将数据从 C# 应用程序发送到网站/网络服务器?

node.js - Npm 安装错误键入 : command not found

angular - 在 Y 轴上显示时间 - 气泡图

javascript - 只需要 Promise 同步性返回,而不是使用 '.then' 时的值