2017-07-25 66 views
1

如何将此AngularJS转换为Angular? 我创建了组件ForgotPassword,并不知道如何正确发送http.post到我的c#控制器。将AngularJS服务转换为Angular

function (window, angular) { 
"use strict"; 

angular.module("Mobile") 
.service("accountService", ["$http", function ($http) { 
return { 

forgotPassword: function (email, success, error) { 
$http.post("Account/ForgotPassword", { Email: email}).success(success).error(error); 
    } 
    } 
}]); 
})(window, window.angular); 

回答

1

您将需要创建一个服务类

app.serivce.ts

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/Rx'; 

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

    public forgotPassword(email: string):Observable<any> { 
    let url:string = 'apiUrl/Account/ForgotPassword'; 
    let body: any = { Email: email } 

    return this.http.post(url, body).map((res:Response) => res.json()); 
    } 
} 

这种方法会从你的component.ts内部调用文件

+0

你的意思是,我不必创建se对照app.service文件? –

+0

@ V.Aliosha是的,你应该。 – Pac0

0

accountComponent.ts

constructor(private accountSer: accountService) 

forgotPasswordButton(){ 
this.accountSer.forgotPassword(value) 
} 

个accountService.ts

import { Injectable, ErrorHandler } from '@angular/core'; 
import { Http, Headers, RequestOptions, Response } from '@angular/http'; 


import 'rxjs/Rx'; 



@Injectable() 
export class UserDetailService { 
    public headers: Headers; 
    constructor(private http: Http) { 
     this.headers = new Headers(); 
     this.headers.append('Content-Type', 'application/json'); 
    } 
    forgotPassword(value){ 
    this.http.post('Account/ForgotPassword', JSON.stringify(value), { headers: this.headers }).subscribe();}} 
+0

我该怎么在es6中做这个'private http:Http'? –

+0

你不能。 “:Http”是打字稿输入。静态类型不是es6中的一个功能 – XGreen

+0

因此,是否有一种方法可以在没有TS的情况下执行此操作? –

1

创建一个服务类

import {Injectable} from '@angular/core'; 
import {Http, Response, Headers} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/observable/throw'; 

@Injectable() 
export class accountService { 

    forgotPassword(param): Observable<any> { 
     return this.http.post('Account/ForgotPassword', 
      JSON.stringify(param), 
      {headers: this.headers}) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 
} 

然后导入到的服务组件

import {accountService} '../../services/accountService ' 

从组件调用你的服务

export class ForgotPasswordComponent implements OnInit { 
    constructor(private http: HttpClient , public httpService: accountService) { 


    forgotPassword() { 
     this.busy = this.httpService.forgotPassword() 
      .subscribe(
       data => { Email:this.email }, 
       error => console.log('error'), 
       () => this.forgotPasswordComplete(null) 

      ); 
    } 

    forgotPasswordComplete(result: any) { 
     //alert('error loading http service'); 
    } 
    } 
}