Angular 2在Onit上获得服务价值

时间:2019-10-17 08:01:10

标签: angular

我有一个名为user-status.service的服务文件,该文件调用一个api以获取值:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpService } from "../../http.service";
import { Router } from "@angular/router";

@Injectable()
export class UserStatusService {

    private _userStatusResource = new BehaviorSubject<any>(null);
    reload$ = this._userStatusResource.asObservable();
    constructor(private router: Router, private httpService: HttpService) { }

    getUserDetails() {
        this.httpService.getUsersStatus()
            .subscribe(
            data => {
                console.log(data);
                this._userStatusResource.next(data.body);
            },
            () => console.log("")
            );
    }
}

现在在要获取值的普通组件上,我似乎无法在oninit上获取值。

import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpService } from "../../http.service";
import { UserStatusService } from '../../shared/services/user-status.service';
import { Subscription } from "rxjs/Rx";

@Component({
  selector: 'app-event-management',
  templateUrl: './event-management.component.html'
})
export class EventManagementComponent implements OnInit {

    userStatus: any;
    private subscription1: Subscription;

    constructor(private httpService: HttpService, private userStatusService: UserStatusService) {

        this.subscription1 = this.userStatusService.reload$
            .subscribe(
            response => {
                this.userStatus = response;
if ((this.userStatus.isDefaultAdmin == false))
                {
                    alert("Do something");
                }
            });

    }

  ngOnInit() {
this.userStatusService.getUserDetails();
    }

  ngOnDestroy() {
      this.subscription1.unsubscribe();
  }

}

来自订阅的值始终为null(永远不会运行“做某事”警报)。如何在运行时从服务中获取价值?

我还应该提到此服务文件的要点是因为我只想在会话中调用一次该api,所以不需要重复调​​用它。

1 个答案:

答案 0 :(得分:3)

尝试将BehaviorSubject更改为Subject,以使对next的首次调用具有值,而不是第一次订阅时获得的null,这是默认行为

此外,您可以在订阅时检查null的值:

this.subscription1 = this.userStatusService.reload$
  .subscribe(response => {
      if (!response)
          return;
      this.userStatus = response;
      if ((this.userStatus.isDefaultAdmin == false)) {
          alert("Do something");
      }
});