简体   繁体   English

将服务从Angular 2/4更新为Angular 7

[英]Updating Services from Angular 2/4 to Angular 7

Updating Services to function in Angular 7. I have two functions I am reviewing to start with - A Login function and a Get User Information function. 更新服务以在Angular 7中运行。我有两个我正在审查的函数 - 一个登录功能和一个获取用户信息功能。

I have been using the modules import { Http, Response, RequestOptionsArgs, Headers } from '@angular/http'; 我一直在使用'@ angular / http'中的模块import {Http,Response,RequestOptionsArgs,Headers};

I cannot find guidance on a migration. 我无法找到有关迁移的指导。

    login(request: LoginUserRequest): Observable<LoginUserResponse> {
    var options:RequestOptionsArgs ={};
    options.headers = new Headers();
    options.headers.append("content-type", "application/x-www-form-urlencoded");
    var  actual_request:string = "grant_type=password" + 
    "&username=" + request.username + "&password=" + request.password;
    return this._http.post(this._loginUserUrl, actual_request, options)
        .map((response: Response) => <LoginUserResponse> response.json())
        .catch(this.handleError);
}


  getUserContext(): Observable<UserContextResponse> {
    var options = this.getOptionHeader();
    return this._http.get(this._users + "/current/context", options)
        .map((response: Response) => <UserContextResponse> response.json())
        .do((data) => {
            this._refreshUserContext(data);
            this._userContext = data;
            this.isuserContextReady.next(data);
        })
        .catch(this.handleError);
 }

Full Service.ts: 全面服务:

    import { Injectable } from '@angular/core';
import { Http, Response, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import { LoginUserRequest, LoginUserResponse, UserContextResponse } from "./membership.messages";
import { BaseService } from "../../app/membership/membership.base-service";
import { UserProfileService } from "../../app/userprofile.service";

@Injectable()
export class MembershipService extends BaseService {
    private _loginUserUrl:string;
    private _users:string;
    public _userContext: UserContextResponse;
    loggedIn:boolean;
    public isuserContextReady: BehaviorSubject<UserContextResponse> = new BehaviorSubject<UserContextResponse>(null);
    constructor(private _http: Http,
    private _userProfileService:UserProfileService) { 
        super();
        this._loginUserUrl = this.baseurl + '/token';
        this._users = this.baseurl + '/api/users';
        var auth_token = sessionStorage.getItem('auth_token');
        this.loggedIn= (auth_token)?true:false;
    }

    getUserContext(): Observable<UserContextResponse> {
        var options = this.getOptionHeader();
      //  console.log("at get user context");
        return this._http.get(this._users + "/current/context", options)
            .map((response: Response) => <UserContextResponse> response.json())
   //     .do(data => console.log('All: ' +  JSON.stringify(data)))
            .do((data) => {
                this._userContext = data;
                this.isuserContextReady.next(data);
            })
            .catch(this.handleError);
     }

    login(request: LoginUserRequest): Observable<LoginUserResponse> {
        var options:RequestOptionsArgs ={};
        options.headers = new Headers();
        options.headers.append("content-type", "application/x-www-form-urlencoded");
        var  actual_request:string = "grant_type=password" + 
        "&username=" + request.username + "&password=" + request.password;
        return this._http.post(this._loginUserUrl, actual_request, options)
            .map((response: Response) => <LoginUserResponse> response.json())
            .catch(this.handleError);
    }

}

Basically, you need to change your Http module with the new package HttpClient (and the others) from @angular/common/http . 基本上,您需要使用@angular/common/http的新包HttpClient(以及其他包)更改Http模块。 Your current code would look like this: 您当前的代码如下所示:

import { HttpClient, HttpResponse, httpOptions, HttpHeaders} from '@angular/common/http'; //you need to change all these imports

// your 'login' method may look like this
login(request: LoginUserRequest): Observable < LoginUserResponse > {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded'
    })
  };

  const actual_request = new FormData();
  formData.append('grant_type', 'password');
  formData.append('username', request.username);
  formData.append('password', request.password);

  return this._http.post(this._loginUserUrl, actual_request, httpOptions)
    .subscribe(
      (response: Response) => { < LoginUserResponse > response.json(); },
      (error: any) => { this.handleError(); }
    );
}

Some of the basic things to consider before migrating to angular 7. 迁移到angular 7之前需要考虑的一些基本事项。

From Angular 4, angular is depreciated the Http and maintaining the HttpClient with breaking change to Http . 从Angular 4开始,angular对Http折旧,并维持HttpClientHttp更改。

import { HttpClientModule } from '@angular/common/http';

replace the HttpModule with HttpClientModule in your core module. 用核心模块中的HttpClientModule替换HttpModule

import { HttpClient, HttpHeaders } from '@angular/common/http';

constructor(private _http: HttpClient) {}

getUserContext(): Observable<UserContextResponse> {
    var options = this.getOptionHeader();
    //  console.log("at get user context");
    return this._http.get(this._users + '/current/context', options).pipe(
      tap(data => {
        this._userContext = data;
        this.isuserContextReady.next(data);
      }, catchError(err => err))
    );
  }
  • Also you have to upgrade to rxjs version to 6 to use pipeable operators 此外,您必须将rxjs版本升级到6才能使用可管道运算符
  • response from httpClient is JSON by default so you don't have to map to json again 默认情况下,httpClient的响应是JSON,因此您不必再次map to json
  • catchError Please check the catch operator from this link https://rxjs.dev/api/operators/catchError catchError请从此链接https://rxjs.dev/api/operators/catchError查看catch操作符
  • use HttpHeaders instead of Headers 使用HttpHeaders而不是Headers
  • HttpClient now supports typings so you don't required Response in Http . HttpClient现在支持打字,所以你不需要Http Response Define your response type in this._http.get<ResponseInterface>(url, options) this._http.get<ResponseInterface>(url, options)定义您的响应类型this._http.get<ResponseInterface>(url, options)
  • there is no interface for RequestOptionsArgs in HttpClient HttpClient没有RequestOptionsArgs接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM