【问题标题】:http.post not working in angular 2http.post 在角度 2 中不起作用
【发布时间】:2017-04-13 02:38:16
【问题描述】:

为什么我的 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{}

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 控制台有错误吗? AuthenticationService 上面有 Injectable 装饰器吗?
  • 不,有一些错误,但我的应用程序会快速返回登录页面。还有更多。我在 URL 上得到了这个:localhost:3000/?username=test&password=test。那么,既然它是一个发布请求,为什么它会在 URL 中显示参数
  • 告诉我您在调用 API 时希望在 URL 中看到什么。
  • 我期待一个结果,无论是成功还是错误响应。但我不打算在发出 POST 请求时看到 URL 中的参数。
  • 您是否在 chrome 开发工具中检查了您的网络选项卡?这样我们就可以了解您是否真的进行了邮寄电话..

标签: javascript http angular error-handling


【解决方案1】:
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) { }

然后你可以用它来 this._http.post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2015-04-25
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多