如何将此AngularJS转换为Angular?
我创建了名为ForgotPassword
的组件,但不知道如何正确地将http.post
发送到我的c#控制器。
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);
答案 0 :(得分: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文件中调用此方法
答案 1 :(得分: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');
}
}
}
答案 2 :(得分: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();}}