angular 5 behaviorubject不使用http

时间:2018-03-28 04:11:11

标签: javascript angular angular5 behaviorsubject

我正在尝试从服务器获取用户类型并基于用户显示数据的角色。 http服务正在运行文件并返回所需的数据。我有两个组成部分。登录和家庭组件。登录后,设置布尔变量以确定用户是管理员还是用户。登录功能显示isAdmin变量为true。但家庭组件显示它是假的。我使用actsubject和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);
      });


  }

}

1 个答案:

答案 0 :(得分:0)

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

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

在子组件中应该是这样的

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

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

{{1}}