【问题标题】:Subscribe Value of *ngIf is not Updating*ngIf 的订阅值未更新
【发布时间】:2019-08-15 18:27:03
【问题描述】:

这是我正在尝试做的基本想法..!

我的应用程序中的所有模块都有一个全局导航栏。但是当我转到特定组件时,我想从我的导航栏中隐藏搜索栏。为此,我使用了创建全局变量并订阅它的方法(从导航栏订阅)

location.service.ts 是我的全局变量服务

import { Injectable } from '@angular/core';
import { Observable ,of as observableOf} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  private createnewproject: boolean = false;
  constructor() { }

public getcurrentlocation(): Observable<boolean>
{
  return  observableOf( this.createnewproject);
}

public setcurrentlocation(status:boolean)
{
  this.createnewproject = status ;
}

public checkvalue():boolean
{
  return this.createnewproject;
}

}

//createnewproject 最初为 false,一旦进入特定模块,我会将其设置为 true

这是我的导航栏类,这就是我订阅它的方式

import { Component, OnInit } from '@angular/core';
import { ConstantsService } from '../common/services/constants.service';
import { LocationService} from '../common/services/location.service';
import { observable } from 'rxjs';

@Component({
  selector: 'app-ibrainmart-header',
  templateUrl: './ibrainmart-header.component.html',
  styleUrls: ['./ibrainmart-header.component.css']
})
export class IbrainmartHeaderComponent implements OnInit {
  oncreateproject: boolean;
  constructor( private projectloaction: LocationService) { }

  ngOnInit()
  {


    const oncreate = this.projectloaction.getcurrentlocation().subscribe(observable => { this.oncreateproject = observable;});

  }

}

这就是我计划使用 *ngIf 从代码中隐藏搜索栏的方式

 <div class="row" *ngIf = "!oncreateproject">
      <div class="col-md-12">
          <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                  <div class="input-group mb-3">
                  <input type="text" class="form-control"  placeholder="Search anything ..!" aria-label="Searchbar" aria-describedby="">
                      <div class="input-group-append">
                      <button class="btn btn-outline-light" type="button" id="btnsearch" ><i class="fa fa-search"></i>{{oncreateproject}}</button>
                      </div>


                  </div>
          </nav>
      </div>
  </div>

这就是我在到达特定页面后将全局变量设置为 true 的方式

import { Component, OnInit } from '@angular/core';
import { ConstantsService } from 'src/app/common/services/constants.service';
import { LocationService } from 'src/app/common/services/location.service';

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

  createnewproject: boolean;

  constructor( private oncreateproject: LocationService) {

   this.oncreateproject.setcurrentlocation(true);
   console.log('Globle Value:' + this.oncreateproject.checkvalue());
   }

  ngOnInit()
  {

  }


}

但是当我转到此页面时,全局值正在更新但 Serach 栏没有隐藏,有人可以帮我找到我在哪里做错了..?

【问题讨论】:

  • rxjs 只会创建一个可观察的值基础,但不会与属性值的任何更新同步
  • 您好 Aruna Liyanaarachchi,如果有任何答案解决了您的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。 ??????

标签: angular angular-services angular-ng-if


【解决方案1】:

您需要使用 rxjs 主题的函数只是创建一个可观察的值基础,但不会同步对属性的任何更改,即为什么我认为是使用主题的最佳情况

import { Injectable } from '@angular/core';
import { Observable ,Subject , from} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LocationService {
  private createnewproject: Subject<boolean>= new Subject();
  constructor() { }


public getcurrentlocation(): Observable<boolean>
{
  return  from(this.createnewproject);
}

public setcurrentlocation(status:boolean)
{
  this.createnewproject.next(status);
}


}

IbrainmartHeaderComponent

export class IbrainmartHeaderComponent implements OnInit {

  // set initial value in case you want to see the search bar by default 
  oncreateproject: boolean = true;

  constructor( private projectloaction: LocationService) { }

  ngOnInit()
  {
    this.projectloaction.getcurrentlocation().subscribe(state => { 
      this.oncreateproject = state;
    });

  }

}

subjects

【讨论】:

    【解决方案2】:

    我会使用 BehaviorSubject,所以它拥有一个初始值,并且可以在视图中使用 async 来解析该值。

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class LocationService {
      private searchBarVisibility$ = new BehaviorSubject(true);
      constructor() { }
    
      public getcurrentlocation(): Observable<boolean> {
        return from(this.searchBarVisibility$);
      }
    
      public setcurrentlocation(status: boolean) {
        this.searchBarVisibility$.next(status);
      }
    
    }
    

    然后隐藏搜索栏

     <div class="row" *ngIf = "oncreateproject | async">
          <div class="col-md-12">
              <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                      <div class="input-group mb-3">
                      <input type="text" class="form-control"  placeholder="Search anything ..!" aria-label="Searchbar" aria-describedby="">
                          <div class="input-group-append">
                          <button class="btn btn-outline-light" type="button" id="btnsearch" ><i class="fa fa-search"></i>{{oncreateproject | async}}</button>
                          </div>
                      </div>
              </nav>
          </div>
      </div>
    

    IbrainmartheaderComponent

    import { Component, OnInit } from '@angular/core';
    // import { ConstantsService } from '../constants.service';
    import { LocationService} from '../location.service';
    import { Observable } from 'rxjs';
    
    @Component({
      selector: 'app-ibrainmart-header',
      templateUrl: './ibrainmart-header.component.html',
      styleUrls: ['./ibrainmart-header.component.css']
    })
    export class IbrainmartheaderComponent implements OnInit {
      oncreateproject: Observable<boolean>;
      constructor( private projectlocation: LocationService) { }
    
      ngOnInit()
      {
        this.oncreateproject = this.projectlocation.getcurrentlocation();
      }
    
    }
    

    创建新项目组件

    import { Component, OnInit } from '@angular/core';
    // import { ConstantsService } from 'src/app/common/services/constants.service';
    import { LocationService } from '../location.service';
    
    @Component({
      selector: 'app-createnewproject',
      templateUrl: './createnew-project.component.html',
      styleUrls: ['./createnew-project.component.css']
    })
    export class CreatenewprojectComponent {
    
      createnewproject: boolean;
    
      constructor(private projectlocation: LocationService) {
        this.projectlocation.getcurrentlocation().subscribe(value =>
              console.log('Globle Value:' + value)
        );
        this.projectlocation.setcurrentlocation(true);
      }
    
    }
    

    【讨论】:

    • 嗨,在getcurrentlocation 中,您只需自行返回主题,最好使用 from,因此主题保持私密,这就是我在回答中使用 from 的原因?
    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2019-11-21
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多