Почему подписка на тему не работает в Angular 9 - PullRequest
1 голос
/ 30 мая 2020

У меня есть тема, определенная в службе аутентификации. Когда я хочу переместить информацию о пользователе в другой компонент, подписка не работает и не работает. Я пробовал использовать его в разных хуках, но опять же бесполезно. Я также использовал BehaviorSubject, но возвращается null.

Кто-нибудь знает, в чем проблема?

auth.service.ts

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {AuthModel} from '../Infrastructure/Models/authModel';
import {RegisterUserDeviceModel} from '../Infrastructure/Models/RegisterUserDeviceModel';
import {ResponseModel} from '../Infrastructure/Models/responseModel';
import {RegisterUserDeviceResponseModel} from '../Infrastructure/Models/registerUserDeviceResponseModel';
import {LoginResponseModel} from '../Infrastructure/Models/LoginResponseModel';
import {RegisterDeviceDataMosel} from '../app.component';
import {BehaviorSubject, Subject, throwError} from 'rxjs';
import {UserDataModel} from '../Infrastructure/Models/UserDataModel';
import {catchError, tap} from 'rxjs/operators';
import {RoleEnum} from '../Infrastructure/Enums/RoleEnum';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    devicecode: string = (<RegisterDeviceDataMosel> JSON.parse(localStorage.getItem('RegisterDeviceData'))).devicecode;
    user = new Subject<UserDataModel>();

constructor(private _http: HttpClient) {
}

Signin(data: AuthModel) {
    let _headers = new HttpHeaders();
    _headers = _headers.append('Content-Type', 'application/json');
    _headers = _headers.append('Access-Control-Allow-Origin', '*');
    _headers = _headers.append('X-Skip-Interceptor', '');
    _headers = _headers.append('device_code', this.devicecode);
    const _options = {headers: _headers};

    return this._http.post<ResponseModel<LoginResponseModel>>('http://localhost:5000/account/login', data, _options)
        .pipe( catchError(this.handelError) , tap(resData => {
            this.handleAuth(data.username, resData.response.access_token, resData.response.refresh_token
                , resData.response.role, resData.response.expires_in);
        }));
}

AutoLoading(): boolean {
    debugger;
    const userData: {
        username: string,
        access_token: string,
        refresh_token: string,
        role: RoleEnum,
        _tokenexpirationDate: string
    } = JSON.parse(localStorage.getItem('userData'));
    if (!userData) {
        return false;
    }
    const loadUser = new UserDataModel(userData.username, userData.access_token, userData.refresh_token
        , userData.role, new Date(userData._tokenexpirationDate));
    if (loadUser.token) {
        this.user.next(loadUser);
        return true;
    }
}

private handleAuth(username, token, refresh_token, role, expiresin) {
    const expirationDate = new Date(new Date().getTime() + +expiresin * 60000);
    const user = new UserDataModel(username, token, refresh_token
        , role, expirationDate);
    debugger;
    this.user.next(user);
    localStorage.setItem('userData', JSON.stringify(user));
}

private handelError(errorResponse: HttpErrorResponse){
    return throwError(errorResponse);
}
}

component

import {AfterViewChecked, AfterViewInit, Component, OnDestroy, OnInit} from '@angular/core';
import * as momenthijri from 'moment-hijri';
import {AuthService} from '../../auth/auth.service';
import {Subscription} from 'rxjs';



@Component({
  selector: 'app-footer',
  styleUrls: ['./footer.component.scss'],
  templateUrl: './footer.component.html',
  providers: [AuthService]
})
export class FooterComponent implements OnInit , OnDestroy {
  private userSub: Subscription ;
  nowDate = new Date();
  hijri;
  public userName;
  public role;

  constructor(private authService: AuthService) {
  }

  ngOnInit(): void {
    this.hijri = momenthijri(this.nowDate.toString()).format('iYYYY/iM/iD');
    this.userSub = this.authService.user.subscribe( res =>{
      debugger;
      this.userName = res.username ;
      this.role = res.role;
    });
  }

  ngOnDestroy(): void {
    this.userSub.unsubscribe();
  }
}

Всем спасибо за помощь

1 Ответ

0 голосов
/ 30 мая 2020

Это происходит потому, что Subject не хранит данные внутри, и вы должны подписаться на перед тем, как предоставит данные в вашей теме. Кроме того, вы можете использовать BehaviorSubject, который хранит данные внутри, и все время, когда вы подписываетесь на него, вы будете получать эти данные, но вы должны указать начальное значение.

С другой стороны, вы можете смоделировать BehaviorSubject без начального значения с помощью user = new ReplaySubject<UserDataModel>(1), который сохранит последние данные и будет возвращать их каждый раз при подписке. Надеюсь, мои объяснения понятны :)

...