Импорт из параметров заголовка http и устаревший запрос на угловой - PullRequest
0 голосов
/ 20 декабря 2018

Мне нужно использовать следующий код, который я взял из Интернета, но я думаю, что он довольно старый и говорит, что импорт 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 голосов
/ 20 декабря 2018

С 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 в ваш сервис constructor: constructor(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.

0 голосов
/ 20 декабря 2018

Для угловых 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 };

...