On-change ng2-select option load component in dashboard angular4 - javascript

I am new to Angular 4, I have been working in a project since couple of weeks.
My requirement is when i select a option in ng2-select box i want to load
a separate component in dashboard.
I have created two components to load content based on options in select box.
The first value 0 or first option text should be display default.
When i change options in select i want load two components to respective of their components.
menu.component.html
<ng-select (change)="onChangeSelect($event)" [allowClear]="true"
[items]="items"
[disabled]="disabled"
(data)="refreshValue($event)"
(selected)="selected($event)"
(removed)="removed($event)"
(typed)="typed($event)"
placeholder="Select">
</ng-select>
menu.component.ts
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery/dist/jquery.min.js';
import {SelectModule} from 'ng2-select';
import { Router} from '#angular/router';
import { ActivatedRoute } from '#angular/router';
declare var jQuery:any;
#Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css'],
})
export class MenuComponent implements OnInit {
onchangeOption:string = '';
public items:Array<string> = ['Program Summary', 'Portfolio Summary']
private value:any = {};
private _disabledV:string = '0';
private disabled:boolean = false;
private get disabledV():string {
return this._disabledV;
}
private set disabledV(value:string) {
this._disabledV = value;
this.disabled = this._disabledV === '1';
}
public selected(value:any):void {
console.log('Selected value is: ', value);
}
public removed(value:any):void {
console.log('Removed value is: ', value);
}
public typed(value:any):void {
console.log('New search input: ', value);
}
public refreshValue(value:any):void {
this.value = value;
}
showHide: boolean;
constructor(private route: ActivatedRoute, private router:Router) {
}
ngOnInit() {
}
showHideMenu(){
this.showHide = !this.showHide;
}
HideMenu(){
this.showHide = false;
console.log("out")
}
onChangeSelect(event){
this.onchangeOption = event.target.value;
console.log(event);
if(this.onchangeOption == 'Portfolio Summary'){
this.router.navigate(['programs']);
}else{
this.router.navigate(['summaries']);
}
}
}
app.module.ts
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: '', redirectTo: 'programs', pathMatch: 'full' },
{ path: ':id', component: ProgramsComponent },
/*{ path: 'id', component:ChartsComponent }*/
{ path: 'dashboard/summaries', component:SummariesComponent }
]
}

Related

In Angular why will my Dynamic Tabs / Tab Panes work initially but not after update?

I am currently using version 3.4 of CoreUI for my Angular App and I am attempting to use their Tabs setup.
Currently it works fine if I populate the tabs oninit but if I update them it breaks. The entire purpose of being able to use this is to have a dynamic list of tabs and content in those tabs so I am at a loss for why this wouldn't work.
I made a very dumbed down version below to show what I am trying. Note that the first instance of this._tabs works fine, after my await calls when I update to the second version it fails to display correctly.
HTML
<c-card>
<c-card-header>
Tabs <code><small>nav-underline</small></code>
</c-card-header>
<c-card-body>
<c-tabset class="nav-underline nav-underline-primary">
<c-tablist>
<c-tab *ngFor="let tab of tabs" >
{{tab.header}}
</c-tab>
</c-tablist>
<c-tab-content>
<br>
<c-tab-pane *ngFor="let tab of tabs">
<p>
{{tab.panel}}
</p>
</c-tab-pane>
</c-tab-content>
</c-tabset>
</c-card-body>
</c-card>
Component
import { Component, OnInit } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { DbService, DashCpResult, IssuerGroup } from '../../db.service';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
// Arrays
DashCpResults: Array<DashCpResult>;
private _setTab: number;
get setTab() {
return this._setTab;
}
set setTab(value: number) {
this._setTab = value || 0;
}
private _tabs: any[] = [];
public get tabs() {
return this._tabs;
}
constructor(
private DbService: DbService,
private route: ActivatedRoute,
private router: Router,
) {
this.setTab = 0;
}
rungetDashCpResult(id) {
return new Promise((resolve) => {
this.DbService.getDashCpResult(id).subscribe(DashCpResults => this.DashCpResults = DashCpResults,
(err) => {
console.log('ERROR: ' + JSON.stringify(err));
},() => {
resolve(1);
});
})
}
async ngOnInit() {
this._tabs = [
{ header: 'Home', panel: 'Home'},
{ header: 'Home2', panel: 'Home2'},
{ header: 'Home3', panel: 'Home3'},
{ header: 'Home4', panel: 'Home4'}
];
// Get Screen detail for Tabs
try { await this.rungetDashCpResult(1); } catch (e) {console.log(e)}
// Update Tabs for a test
this._tabs = [
{ header: 'Home5', panel: 'Home5'},
{ header: 'Home6', panel: 'Home6'},
{ header: 'Home7', panel: 'Home7'},
{ header: 'Home8', panel: 'Home8'}
];
}
}

Retrieving the next item in an array by index in Angular 11

I have a list of employees in a JSON object in my service.ts file. It will be moved to a DB eventually. I know this is not the place for it. It's just for dev purposes. I am able to retrieve the employees by clicking on it and displaying them in a dynamic view component.
However, I want to be able to see the next employee on a button click without having to always go back to the main list. I am able to retrieve the index and increment the index on click. I just can't get the route to display the data for that index.
The HTML is pretty basic a simple button with a click method. The Service file looks like this:
import {HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Employee } from '../models/employee.models';
#Injectable({
providedIn: 'root'
})
export class EmployeesService {
private listEmployees: Employee[] = [...regular json object...];
constructor() { }
getEmployees(): Employee[] {
return this.listEmployees;
}
getEmployee(id: number): Employee {
return this.listEmployees.find(e => e.id === id);
}
}
And my employee.component.ts file
import { ActivatedRoute } from '#angular/router';
import { EmployeesService } from './../../../services/employees.service';
import { Component, OnInit } from '#angular/core';
import { Employee } from 'src/app/models/employee.models';
import { Router } from '#angular/router';
#Component({
selector: 'employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.scss']
})
export class EmployeeComponent implements OnInit {
employee: Employee;
employees: Employee[];
index: number;
private _id: number;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _employeeService: EmployeesService
) { }
ngOnInit() {
this.employees = this._employeeService.getEmployees();
for ( this.index = 1; this.index < this.employees.length + 1; this.index++ ) {
this._route.paramMap.subscribe(params => {
this._id = +params.get('id')
console.log('this index:', this.index);
this.employee = this._employeeService.getEmployee(this._id);
});
}
}
viewNextEmployee() {
if( this.index < this.employees.length ){
this.index = this.index++;
console.log('this index:', this.index);
this._router.navigate(['/team', this._id])
} else {
this.index = 1;
}
}
}
I'm sorry, I can't really reproduce a working code. So many dependencies.

Sharing an object from cone component to another Angular 2

I want to share an object from my first component to the second. I am able to log the 'strVal'(string) defined in the Login Component, in my Home Component but I am unable to log the value of 'abc'(Object) from the Login Component, in the HomeComponent. I am confused why one value from Login Component gets available to Home Component and other does not! The code for Login Component in below
Login.Component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { AuthenticationService } from '../_services/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
loading = false;
error = '';
us: User[];
abc: any[];
strVal: string = "Rehan";
current: any;
constructor(
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
// reset login status
this.authenticationService.logout();
this.getUs();
}
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
if (result) {
this.router.navigate(['/']);
}
else {
alert('Username and Password Incorrect');
this.loading = false;
this.model = [];
this.router.navigate(['/login']);
}
});
}
getUs() {
this.authenticationService.getUsers().subscribe(
res => this.us = res
);
}
chek() {
this.abc = this.us.filter(a => a.Login === this.model.username);
console.log(this.abc);
}
}
Home.Component.ts
import { Component, OnInit, Input } from '#angular/core';
import { AuthenticationService } from '../_services/index';
import { LoginComponent } from '../login/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'home.component.html',
providers: [LoginComponent]})
export class HomeComponent implements OnInit {
users: User[];
constructor(private userService: AuthenticationService, private Log: LoginComponent) { }
ngOnInit() {
this.userService.getUsers().subscribe(
res => this.users = res
);
console.log(this.Log.strVal);
console.log(this.Log.abc);
}
}
Any hint or help will be appreciated. Thanks!

Angular2 call function from another component

I have two components: NgbdAlertCloseable and AlertCtrl. Also I have AppComponent as parent component. What I want is to click a button in AlertCtrl component and create the alert on NgdbAlertCloseable component.
addSuccess() function adds an alert to the view and it worked well while I call it inside of its component. However, I tried to use an EventEmitter to call this function from another component (as suggested here: https://stackoverflow.com/a/37587862/5291422) but it gives this error:
ORIGINAL EXCEPTION: TypeError: self._NgbdAlertCloseable_2_4.addSuccess is not a function
Here are my files:
ngbd-alert-closeable.component.ts
import { Input, Component } from '#angular/core';
#Component({
selector: 'ngbd-alert-closeable',
templateUrl: './app/alert-closeable.html'
})
export class NgbdAlertCloseable {
#Input()
public alerts: Array<IAlert> = [];
private backup: Array<IAlert>;
private index: number;
constructor() {
this.index = 1;
}
public closeAlert(alert: IAlert) {
const index: number = this.alerts.indexOf(alert);
this.alerts.splice(index, 1);
}
public static addSuccess(alert: IAlert) {
this.alerts.push({
id: this.index,
type: 'success',
message: 'This is an success alert',
});
this.index += 1;
}
public addInfo(alert: IAlert) {
this.alerts.push({
id: this.index,
type: 'info',
message: 'This is an info alert',
});
this.index += 1;
}
}
interface IAlert {
id: number;
type: string;
message: string;
}
alert-ctrl.component.ts
import { EventEmitter, Output, Component } from '#angular/core';
import { NgbdAlertCloseable } from './ngbd-alert-closeable.component';
#Component({
selector: 'alert-ctrl',
template: '<button class="btn btn-success" (click)="addSuccessMsg()">Add</button>'
})
export class AlertCtrl {
#Output() msgEvent = new EventEmitter();
public addSuccessMsg(){
this.msgEvent.emit(null);
}
}
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: '<div class="col-sm-4"><alert-ctrl (msgEvent)="ngbdalertcloseable.addSuccess()"></alert-ctrl><ngbd-alert-closeable #ngbdalertcloseable></ngbd-alert-closeable>'
})
export class AppComponent { }
Am I using it wrong? How can I fix that?
Check that the addSuccess function is static and is using non static properties.
Should be:
public addSuccess(alert: IAlert) {
this.alerts.push({
id: this.index,
type: 'success',
message: 'This is an success alert',
});
this.index += 1;
}
And in your view you must pass the IAlert value in this example we'll send that value when we call msgEvent.emit(IAlert).
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: '<div class="col-sm-4"><alert-ctrl (msgEvent)="ngbdalertcloseable.addSuccess($event)"></alert-ctrl><ngbd-alert-closeable #ngbdalertcloseable></ngbd-alert-closeable>'
})
export class AppComponent { }
Then you must send that IAlert, I'll change your AlertCtrl just for demo purpose.
import { EventEmitter, Output, Component } from '#angular/core';
import { NgbdAlertCloseable } from './ngbd-alert-closeable.component';
#Component({
selector: 'alert-ctrl',
template: '<button class="btn btn-success" (click)="addSuccessMsg()">Add</button>'
})
export class AlertCtrl {
currentAlert:IAlert = {id: 0, type: 'success', message: 'This is an success alert'};
#Output() msgEvent = new EventEmitter<IAlert>();
public addSuccessMsg(){
this.msgEvent.emit(this.currentAlert);
}
}
Good luck and happy coding!

Where to put service providers in angular 2 hierarchy so that components can talk to each other using the same instance of service?

Related question:
Observable do not receive the next value in angular2
No provider for service error in angular2, why do I need to inject it in it's parent component?
Using observable talk to other component in angular2, not receiving coming value
I have a PagesService that has a setCurrentPlaylists function, this function will be triggered from other component, it will receive an value of Playlists type, and will console log this value, using the next function pass to other component( I intent to).
My entire code for pages service is:
import { Injectable } from '#angular/core';
import { ApiService } from '../../apiService/api.service';
import { Platform } from '../../platforms/shared/platform.model';
import { Page } from './page.model';
import { Playlists } from '../shared/playlists.model';
import { Subject, BehaviorSubject } from 'rxjs/Rx';
#Injectable()
export class PagesService {
private currentPlaylists: Subject<Playlists> = new BehaviorSubject<Playlists>(new Playlists());
constructor(private service: ApiService) {
this.currentPlaylists.subscribe((v) => console.log(v, 'subscriber from pages service is printing out the incoming value'));
}
getPages(platform: Platform) {
return this.service.getPages(platform.value);
}
setCurrentPage(page: Page) {
this.service.setCurrentPage(page.pageId);
}
getCurrentPage():string {
return this.service.getCurrentPage();
}
getCurrentPlaylists() {
return this.currentPlaylists;
}
setCurrentPlaylists(playlists: Playlists) {
console.log("Pages Service receive an value of playlists:", playlists);
this.currentPlaylists.next(playlists);
}
}
My code for page component is:
import { Component, OnInit, Input, Output, OnChanges, EventEmitter, Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { Platform } from '../platforms/shared/platform.model';
import { Page } from './shared/page.model';
import { Playlists } from './shared/playlists.model';
import { PagesService } from './shared/pages.service';
import { PlaylistService } from '../playlist/shared/playlist.service';
import { Subject,BehaviorSubject } from 'rxjs/Rx';
#Component({
selector: 'pages',
styleUrls: ['app/pages/pages.css'],
templateUrl: 'app/pages/pages.html',
providers: [PagesService, PlaylistService]
})
export class PagesComponent {
#Input() platform: Platform;
#Output() onPlaylistsChange: EventEmitter<Playlists>;
currentPageName: string;
currentPage: Page;
pages: Array<Page>;
playlists: Playlists;
constructor(private pageServer: PagesService, private playlistService: PlaylistService) {
this.pages = [];
this.currentPage = new Page();
this.pageServer.setCurrentPage(this.currentPage);
this.playlists = new Playlists();
this.onPlaylistsChange = new EventEmitter<Playlists>();
}
ngOnInit() {
this.pageServer.getCurrentPlaylists().subscribe((playlists) => {
console.log('subscriber in pages component is printing out the incoming value', playlists);
this.playlists = playlists;
}, error => {
console.log(error);
});
}
getPages(platform: Platform): void {
this.pageServer.getPages(platform)
.subscribe(
res => {
if (res.pages.length > 0) {
this.pages = [];
for (let page of res.pages) {
if (page.pageName !== "Shows" && page.pageName !== "All Shows" && page.pageName !== "Moives" && page.pageName !== "All Movies") {
this.pages.push(page);
}
}
this.currentPage = this.pages[0];
this.pageServer.setCurrentPage(this.currentPage);
this.currentPageName = this.pages[0].pageName;
this.getPlaylist(this.currentPage, this.platform);
} else {
this.pages = [];
this.currentPage = new Page();
this.pageServer.setCurrentPage(this.currentPage);
this.playlists = new Playlists();
this.onPlaylistsChange.emit(this.playlists);
}
},
error => console.log(error)
);
}
getPlaylist(page: Page, platform: Platform): void {
this.currentPage = page;
this.pageServer.setCurrentPage(this.currentPage);
this.playlistService.getPlaylist(page, platform)
.subscribe(
res => {
if (res.hasOwnProperty('pages') && res.pages.length > 0) {
if (res.pages[0].hasOwnProperty('bodyPlaylists') && res.pages[0].hasOwnProperty('headerPlaylists')) {
this.playlists.bodyPlaylists = res.pages[0].bodyPlaylists || [];
this.playlists.headerPlaylists = res.pages[0].headerPlaylists || [];
} else {
this.playlists.bodyPlaylists = [];
this.playlists.headerPlaylists = [];
this.playlists.wholePlaylists = res.pages[0].playlists || [];
}
this.onPlaylistsChange.emit(this.playlists);
} else {
this.playlists = new Playlists();
this.onPlaylistsChange.emit(this.playlists);
}
},
error => console.error(error)
);
}
ngOnChanges() {
// Get all Pages when the platform is set actual value;
if (this.platform.hasOwnProperty('value')) {
this.getPages(this.platform);
}
}
}
When I trigger the setCurrentPlaylists function, the playlists didn't passed to pages component. I need to use that passed value to update pages component's playlists.
This is the console output after I trigger the setCurrentPlaylsts function. No message from pages components.
Any suggestions are appreciated!
I call setCurrentPlaylists function from this component
/// <reference path="../../../typings/moment/moment.d.ts" />
import moment from 'moment';
import { Component, ViewChild, ElementRef, Input, Output, EventEmitter } from '#angular/core';
import { CORE_DIRECTIVES } from '#angular/common';
import { Http, Response } from '#angular/http';
import { MODAL_DIRECTVES, BS_VIEW_PROVIDERS } from 'ng2-bootstrap/ng2-bootstrap';
import {
FORM_DIRECTIVES,
REACTIVE_FORM_DIRECTIVES,
FormBuilder,
FormGroup,
FormControl,
Validators
} from '#angular/forms';
import { PagesService } from '../../pages/shared/pages.service';
import { ApiService } from '../../apiService/api.service';
#Component({
selector: 'assign-playlist-modal',
providers: [PagesService],
exportAs: 'assignModal',
directives: [MODAL_DIRECTVES, CORE_DIRECTIVES, FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES ],
viewProviders: [BS_VIEW_PROVIDERS],
styleUrls: ['app/channel/shared/assignPlaylist.css'],
templateUrl: 'app/channel/modals/assignPlaylistModal.html'
})
export class AssignPlaylistModalComponent {
#ViewChild('assignPlaylistModal') modal: any;
private addPlaylistForm: FormGroup;
private playlistType: string;
private currentPage: string;
private editDate: string;
constructor(private apiService: ApiService, private pagesService: PagesService, fb: FormBuilder) {
this.currentPage = '';
this.editDate = this.apiService.getDate();
this.addPlaylistForm = fb.group({
'longPlaylistName': ['', Validators.required],
'shortPlaylistName': ['', Validators.required],
'startOn': ['', Validators.compose([
Validators.required, this.validTimeFormat
])],
'expireOn': ['', Validators.compose([
Validators.required, this.validTimeFormat
])],
'isExpire': ['']
});
this.addPlaylistForm.controls['startOn'].valueChanges.subscribe((value: string) => {
if (moment(value, 'YYYY-MM-DDThh:mm').isValid()) {
if (this.playlistType == 'dynamic') {
this.apiService.setGlobalStartTime(moment(value).format("YYYYMMDDHHmm"));
}
}
});
this.addPlaylistForm.controls['expireOn'].valueChanges.subscribe((value: string) => {
if (moment(value, 'YYYY-MM-DDThh:mm').isValid()) {
if (this.playlistType == 'dynamic') {
this.apiService.setGlobalEndTime(moment(value).format("YYYYMMDDHHmm"));
}
}
});
}
showModal(type: string) {
this.playlistType = type;
this.currentPage = this.apiService.getCurrentPage();
this.modal.show();
}
validTimeFormat(control: FormControl): { [s: string]: boolean} {
if (!moment(control.value, 'YYYY-MM-DDThh:mm').isValid()) {
return { invalidTime: true};
}
}
setCloseStyle() {
let styles = {
'color': 'white',
'opacity': 1
}
return styles;
}
createNewPlaylist(stDate: string, etDate: string, playlistTitle: string, shortTitle: string, callback?: any):any {
this.apiService.createNewPlaylist(stDate, etDate, playlistTitle, shortTitle)
.subscribe(
data => {
let playlistId = data[0].id;
this.apiService.addPlaylistToPage(playlistId, stDate, etDate, this.apiService.getGlobalRegion(), callback)
.subscribe(
data => {
if (this.apiService.g_platform == 'DESKTOP') {
this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'true' )
.subscribe(
res => {
if (res.hasOwnProperty('pages') && res.pages.length > 0) {
if (res.pages[0].hasOwnProperty('bodyPlaylists') && res.pages[0].hasOwnProperty('headerPlaylists')) {
this.apiService.getCurrentPlaylists().bodyPlaylists = res.pages[0].bodyPlaylists || [];
this.apiService.getCurrentPlaylists().headerPlaylists = res.pages[0].headerPlaylists || [];
console.log('assign playlist component is calling the pages service setCurrentPlaylists function.');
this.pagesService.setCurrentPlaylists(this.apiService.getCurrentPlaylists());
} else {
this.apiService.getCurrentPlaylists().bodyPlaylists = [];
this.apiService.getCurrentPlaylists().headerPlaylists = [];
this.apiService.getCurrentPlaylists().wholePlaylists = res.pages[0].playlists || [];
console.log('assign playlist component is calling the pages service setCurrentPlaylists function.');
this.pagesService.setCurrentPlaylists(this.apiService.getCurrentPlaylists());
}
}
}
);
} else {
this.apiService.getPlaylist(this.apiService.getCurrentPage(), 'false' )
.subscribe(
res => {
if (res.hasOwnProperty('pages') && res.pages.length > 0) {
this.apiService.getCurrentPlaylists().bodyPlaylists = [];
this.apiService.getCurrentPlaylists().headerPlaylists = [];
this.apiService.getCurrentPlaylists().wholePlaylists = res.pages[0].playlists || [];
console.log('assign playlist component is calling the pages service setCurrentPlaylists function.');
this.pagesService.setCurrentPlaylists(this.apiService.getCurrentPlaylists());
}
}
);
}
}
);
},
error => console.log(error)
);
}
onSubmit(form: FormGroup) {
// get start time, the format from input will be like 2016-06-07T00:05
let startTime = moment(form.value.startOn).format("YYYYMMDDHHmm");
let expireTime = moment(form.value.expireOn).format("YYYYMMDDHHmm");
let playlistTitle = form.value.longPlaylistName;
let shortTitle = form.value.shortPlaylistName;
if (this.playlistType == 'smart' || this.playlistType == 'new') {
this.createNewPlaylist(startTime, expireTime, playlistTitle, shortTitle);
}
}
}
This is my component tree:
I am assuming your components tree is as follow:
AssignPlaylistModalComponent (Parent or higher level than PagesComponent in the tree)
PagesComponent (lowest level child as it does not import any directive)
Issue
You should only put your service in the top level (parent) components provider. Though all components still need to do the import and constructor.
Putting the service in a component's provider will create a new copy of the service and share along the component tree downward, not upward.
In the code in question, PagesComponent, as the lowest level child in the tree, with its own provider line, is actually initiating its own copy of PagesService, PlaylistService. So each instance of PagesComponent is basically listening to itself only. It won't receive any messages from others.
Fix
#Component({
selector: 'pages',
styleUrls: ['app/pages/pages.css'],
templateUrl: 'app/pages/pages.html',
providers: [PagesService, PlaylistService] // <--- Delete this line
})
export class PagesComponent {
#Input() platform: Platform;
#Output() onPlaylistsChange: EventEmitter<Playlists>;
Where to put providers
Assume following component tree:
Component A1 (root component)
Component B1
Component C1
Component C2
Component B2
Component C3
Component C4
The easiest way is to put it in A1 providers, all components will be sharing the same service instance, and able to message each other.
If you put it in B1 providers, then only B1, C1 and C2 can talk to each other.
Base on lastest update, the root component of the project is AppComponent.ts. providers should be added in it.
From the code you provided, I cannot see when this method
setCurrentPlaylists(playlists: Playlists) {
console.log(playlists, 'i am here');
this.currentPlaylists.next(playlists);
}
is called. Therefore, your list is empty.
Doing this
this.pageServer.getCurrentPlaylists().subscribe((playlists) => {
console.log(playlists, 'new playlists coming');
this.playlists = playlists;
}, error => {
console.log(error);
});
only creates a subscription to the observable. You need to publish data from somewhere.
In addition, it'd better to move this code
this.pageServer.getCurrentPlaylists().subscribe((playlists) => {
console.log(playlists, 'new playlists coming');
this.playlists = playlists;
}, error => {
console.log(error);
});
to ngOnInit()

Categories

Resources