Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Angular中从行为主体中提取值_Javascript_Angular_Rxjs_Observable - Fatal编程技术网

Javascript 如何在Angular中从行为主体中提取值

Javascript 如何在Angular中从行为主体中提取值,javascript,angular,rxjs,observable,Javascript,Angular,Rxjs,Observable,我为angular应用程序创建了一个帐户服务,它处理登录和注销。这是完美的。但我有一个问题,我用行为主体的可观察性来呈现变量 我试图在使用服务的组件上检索loginstatus值和用户名字符串,但是observable正在返回一个对象,并且从对象中提取字符串时遇到问题。如何从行为主体的观察中提取变量类型 帐户服务 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http

我为angular应用程序创建了一个帐户服务,它处理登录和注销。这是完美的。但我有一个问题,我用行为主体的可观察性来呈现变量

我试图在使用服务的组件上检索loginstatus值和用户名字符串,但是observable正在返回一个对象,并且从对象中提取字符串时遇到问题。如何从行为主体的观察中提取变量类型

帐户服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';


@Injectable({ 
  providedIn: 'root'
})

export class AccountService {
  

  private baseUrlLogin:string = "/api/account/login";

  private loginStatus = new BehaviorSubject<boolean> 
  (this.checkLoginStatus());  
  private userName = new BehaviorSubject<string> localStorage.getItem['username']);

  constructor(
    private http:HttpClient, 
    private router: Router
  ){}

  login(username:string, password:string){
    return this.http.post<any>(this.baseUrlLogin,{username, password}).pipe(
               map(result => {
                  if(result && result.token){
                      localStorage.setItem('loginStatus', '1'); 
                      localStorage.setItem('username', result.username),

                  }
                  return result;
                  
               })
           );

  }

  logout(){
    this.loginStatus.next(false);
    localStorage.setItem('loginStatus', '0');  
    localStorage.removeItem('username'),
    localStorage.clear();

    //now redirect to the login page... 
    this.router.navigate(['/login']);
    console.log("logged out successfully...");
  }

   
  get isLoggedIn(){
    return this.loginStatus.asObservable(); 
  }

  get currentUserName(){
    return this.userName.asObservable();  
  }

}
使用服务的组件

import { Component, Input, OnInit } from '@angular/core';
import { AccountService } from 'src/app/services/account.service';
import { Observable } from 'rxjs';

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

  pgtitle:string = "SCB Dashboard";

  loginStatus$ : Observable<boolean>;
  username$ : Observable<string>;

  constructor(
    private acc:AccountService
  ){}

  ngOnInit() {
   this.loginStatus$ = this.acc.isLoggedIn;
   this.username$ = this.acc.currentUserName;
   

   console.log(this.loginStatus$);  //here it ruturns an object
   console.log(this.username$);   //and here too... 

  }

}
console.log返回一个对象,但是如何检索变量并在控制器中使用它们,因为它们属于可观察类型?

您需要订阅可观察对象以从中获取值:

this.loginStatus$.subscribe(value => {
   console.log(value); // access value
});

Rxjs Behavior Subject有一个可观察的方法,您可以从中生成可观察的对象

let sourceSubject = new BehaviourSubject();
let source$ = sourceSubject.asObservable();

source$.subscribe(result => // Your data)

// Update the BehaviourSubject

sourceSubject.next(newValue);
试试这个:

get isLoggedIn(){
  return this.loginStatus.value; 
}

get currentUserName(){
  return this.userName.value;  
}
这也应该起作用:

  ngOnInit() {
   this.loginStatus$ = this.acc.isLoggedIn.pipe(
     tap(status => console.log(status))
   );
   this.username$ = this.acc.currentUserName.pipe(
     tap(userName => console.log(userName))
   );

  }

假设您订阅了某个地方,例如使用异步管道。

this.username$.subscribevalue=>{console.logvalue};这个.loginStatus$.getValue和这个.username$.getValue会起作用,或者就是这个.loginStatus$.value和这个.username$.value。是的,这应该能起作用。这里有一个到相应文档的链接:行为主体已经是可观察的,无需使用asobservable创建新的可观察对象。如果此代码在服务中,那么最好使用这样的代码。然后将Subject/BehaviorSubject标记为private和Observable public,以便组件代码可以访问Observable,但不能直接将信息注入流。