angular 5 个行为主体不支持 http

angular 5 behaviorsubject not working with http

我正在尝试从服务器获取用户类型并根据用户角色显示数据。 http 服务是 运行 文件并返回所需的数据。我有两个组成部分。登录和主页组件。登录后,将设置一个布尔变量来决定用户是 Admin 还是 User。登录功能显示 isAdmin 变量为真。但是 home 组件将其显示为 false。我正在使用 behaviorsubject 和 observable 来同步数据。

服务

import { Injectable } from '@angular/core';
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";
import {IPosts} from "./posts";
import {IUser} from "./user";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class ExamService {

  public isAdmin = new BehaviorSubject<boolean>(false);
  cast = this.isAdmin.asObservable();


  private _postsURL = "http://localhost:3292/examservice.svc/ExamQs";
  private _userURL = "http://localhost:3292/examservice.svc/GetUser";

 constructor(private http: Http) {
  }

  getPosts(): Observable<IPosts[]> {
      return this.http
          .get(this._postsURL)
          .map((response: Response) => {
                 return <IPosts[]>response.json();
         })
          .catch(this.handleError);
  }

  getUser(user:string,pass:string): Observable<IUser[]> {
      return this.http
          .get(this._userURL+"/"+user+"/"+pass)
          .map((response: Response) => {
              return <IUser[]>response.json();
          })
          .catch(this.handleError);
  }

  checkAdmin(data){
    this.isAdmin.next(data);
  }

  private handleError(error: Response) {
      return Observable.throw(error.statusText);
  }
}

登录组件

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ExamService } from "../exam.service";
import {IPosts} from "../posts";
import {IUser} from "../user"; 

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ ExamService ]
})


export class LoginComponent implements OnInit {
  _postsArray: IPosts[];
  _userArray: IUser[];
  ifuser: boolean = false;
  Name: string;
  Pass: string;
  validated: boolean = true;


  constructor(private apiSerivce: ExamService,private router:Router) { }

  getPosts(): void {

        this.apiSerivce.getUser(this.Name,this.Pass)
            .subscribe(
            resultArray => {
              this._userArray = resultArray;

              if(this._userArray[0].Role == "Admin")
              {
                this.ifuser = true;
                this.apiSerivce.checkAdmin(this.ifuser); 
              }
              else
              {
                this.apiSerivce.checkAdmin(this.ifuser);
                this.router.navigate(['']);
              }

            },
              error => console.log("Error :: " + error)
            )
            console.log(this.ifuser);
            this.router.navigate(['']);


    }

    ngOnInit(): void {

      this.apiSerivce.cast.subscribe(data => 
    {
          this.validated = data;
          console.log("Login " + this.validated);
        });


    }
  }

主页组件

import { Component, OnInit } from '@angular/core';
import { ExamService } from "../exam.service";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [ ExamService ]
})
export class HomeComponent implements OnInit {
  validated: boolean;
  constructor(private apiSerivce: ExamService) { }

  ngOnInit() {
    this.apiSerivce.cast.subscribe(data => 
      {
        this.validated = data;
        console.log("Home " + this.validated);
      });


  }

}

我找到了解决这个问题的方法。不要在子组件中将服务添加为提供者,而是在作为父组件的 app.component.ts 文件中添加提供者。所以而不是

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [ ExamService ]
})

在子组件中应该是这样的

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})

在app.component.ts文件中应该是这样的

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ ExamService ]
})