简体   繁体   中英

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.

I have been using the modules import { Http, Response, RequestOptionsArgs, Headers } from '@angular/http';

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 . 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.

From Angular 4, angular is depreciated the Http and maintaining the HttpClient with breaking change to Http .

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

replace the HttpModule with HttpClientModule in your core module.

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
  • response from httpClient is JSON by default so you don't have to map to json again
  • catchError Please check the catch operator from this link https://rxjs.dev/api/operators/catchError
  • use HttpHeaders instead of Headers
  • HttpClient now supports typings so you don't required Response in Http . Define your response type in this._http.get<ResponseInterface>(url, options)
  • there is no interface for RequestOptionsArgs in HttpClient

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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