从http标头选项导入,并在angular

时间:2018-12-20 15:52:30

标签: angular http-headers rxjs angular-http angular-httpclient

我需要使用以下从Internet上获取的代码,但是我认为它已经很老了,并且它说HTTP导入已被弃用,我该如何解决? 它给我所有的HTTP导入错误,如果我更改为@ angular / comon / http,我不知道如何更改hhtp标头和在register方法中进行请求。

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

import { UserRegistration } from '../models/user.registration.interface';
import { ConfigService } from '../utils/config.service';

import {BaseService} from "./base.service";

import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx'; 

// Add the RxJS Observable operators we need in this app.
import '../../rxjs-operators';

@Injectable()

export class UserService extends BaseService {

  baseUrl: string = '';

  // Observable navItem source
  private _authNavStatusSource = new BehaviorSubject<boolean>(false);
  // Observable navItem stream
  authNavStatus$ = this._authNavStatusSource.asObservable();

  private loggedIn = false;

  constructor(private http: Http, private configService: ConfigService) {
    super();
    this.loggedIn = !!localStorage.getItem('auth_token');
    // ?? not sure if this the best way to broadcast the status but seems to resolve issue on page refresh where auth status is lost in
    // header component resulting in authed user nav links disappearing despite the fact user is still logged in
    this._authNavStatusSource.next(this.loggedIn);
    this.baseUrl = configService.getApiURI();
  }

    register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
    let body = JSON.stringify({ email, password, firstName, lastName,location });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.baseUrl + "/accounts", body, options)
      .map(res => true)
      .catch(this.handleError);
  }  

   login(userName, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
      this.baseUrl + '/auth/login',
      JSON.stringify({ userName, password }),{ headers }
      )
      .map(res => res.json())
      .map(res => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      })
      .catch(this.handleError);
  }

  logout() {
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
    this._authNavStatusSource.next(false);
  }

  isLoggedIn() {
    return this.loggedIn;
  }

  facebookLogin(accessToken:string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let body = JSON.stringify({ accessToken });  
    return this.http
      .post(
      this.baseUrl + '/externalauth/facebook', body, { headers })
      .map(res => res.json())
      .map(res => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      })
      .catch(this.handleError);
  }
}

2 个答案:

答案 0 :(得分:0)

对于Angular 4+,请尝试:

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

constructor(private http: HttpClient)

let headers = new HttpHeaders ({ 'Content-Type': 'application/json' });

private options = { headers: this.headers };

答案 1 :(得分:0)

Angular 4.3开始,实施了一个更强大的新Http Client

使用方法:

步骤1: import在您的@ngModule中: import { HttpClientModule } from '@angular/common/http';

步骤2:将其导入您的imports中: @NgModule({ imports: [HttpClientModule] })

步骤3:转到处理http操作的服务,并导入HttpClient和HttpHeaders: import { HttpClient, HttpHeaders } from '@angular/common/http';

步骤4:在服务HttpClient中注入constructorconstructor(private httpClient: HttpClient)

register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> { 

  let body = JSON.stringify({ email, password, firstName, lastName,location });
  let headers = new HttpHeaders({ 'Content-Type': 'application/json' }); 
  let options = { headers: headers }; 
  return this.httpClient.post(this.baseUrl + "/accounts", body,      
                                  options).pipe(map(res => true));
}

不要忘记从map导入rxjs/operators