Lajith
Lajith

Reputation: 1877

Observable in angular service

Am making my menu dynamic ..am refering [dynamic menu core ui][1]

This is my service class

import { Injectable } from '@angular/core';
import { HttpClient,HttpParams  } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AuthService } from '../services/auth.service';

import { INavData} from 'src/app/shared/models/Security';
import { Result} from 'src/app/shared/models/Result';

const baseUrl = `${environment.apiUrl}/Menu`;

@Injectable()

export class SidebarService {
  
  items$: Observable<INavData[]>;

  constructor(private httpClient: HttpClient, private authService: AuthService) {
   var user= authService.userValue;
    
   this.items$ = this.getSidebarItems(user.id)
    
  }

private getSidebarItems(userid: number): Observable<INavData[]>   {

      let params = new HttpParams();
      params = params.set('userId', userid.toString());
      var result = this.httpClient.get<INavData[]> (`${baseUrl}/GetMenusByUserId`,{params});
        return result;
  }

}

Api i am getting data ..but items not updating

[![enter image description here][2]][2]

Am new to angular and rxjs.. pls let me know why items is null?

This my html

 <app-sidebar-nav [navItems]="sidebar.items$ | async" [perfectScrollbar] [disabled]="sidebarMinimized"></app-sidebar-nav>
    

My Component class : here iam inject service $items and injecting like above line in html..

import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';
//import { navItems } from '../../_nav';
import { Router } from '@angular/router';

import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { SidebarService } from 'src/app/core/services/sidebar-service';


@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html'
})
export class LayoutComponent implements OnDestroy {

  public sidebarMinimized = true;
  private changes: MutationObserver;
  public element: HTMLElement;


  constructor(
    private router: Router,
    private authService: AuthService,
    private sidebar: SidebarService,
    
    @Inject(DOCUMENT) _document?: any)
     {  
    
      
      this.changes = new MutationObserver((mutations) => {
        this.sidebarMinimized = _document.body.classList.contains('sidebar-minimized');
      });
      this.element = _document.body;
      this.changes.observe(<Element>this.element, {
        attributes: true,
        attributeFilter: ['class']
      });
    
  }

  ngOnDestroy(): void {
    this.changes.disconnect();
  }

  logout() {
    this.authService.logout();
    this.router.navigateByUrl('/login');
  }
}

Upvotes: 0

Views: 314

Answers (1)

Miyas Mohammed
Miyas Mohammed

Reputation: 486

try to call API`s from service file like this:-

import { Injectable } from '@angular/core';
import { HttpClient,HttpParams  } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AuthService } from '../services/auth.service';

import { INavData} from 'src/app/shared/models/Security';
import { Result} from 'src/app/shared/models/Result';

const baseUrl = `${environment.apiUrl}/Menu`;

@Injectable()

export class SidebarService {
  constructor(private httpClient: HttpClient) {
  }

getSidebarItems(userid: number): Observable<INavData[]> {
let params = new HttpParams();
params = params.set("userId", userid.toString());
return this.httpClient.get<INavData[]>(
  `${baseUrl}/GetMenusByUserId`,
  { params }
);
}}

From component you have to call like this.

items:INavData[] = []
constructor(
private router: Router,
private authService: AuthService,
private sidebar: SidebarService,

@Inject(DOCUMENT) _document?: any)
 {  

  
  this.changes = new MutationObserver((mutations) => {
    this.sidebarMinimized = _document.body.classList.contains('sidebar-minimized');
  });
  this.element = _document.body;
  this.changes.observe(<Element>this.element, {
    attributes: true,
    attributeFilter: ['class']
  });
this._storage.localStorageGet('daimler_user').then((res: any) => {
  this.userdata = JSON.parse(res);
  this.fullName = (this.userdata[0].FullName == '') ? this.userdata[0].UserName : this.userdata[0].FullName;
  this.userid = this.userdata[0].ID;
this.sidebar.getSidebarItems(this.userid).subscribe(res=>{
this.items= res;
});
});

  }

Upvotes: 1

Related Questions