【发布时间】: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