my question is how to replay the hisotory of vehicle on leaflet map i have plot the polyline on map but maker is not poloting the marker should plot according to start and stop button i have done this code give me suggesstion how to add anymation marker on map the marker paly using button and stop also using button
import { Component, ElementRef, NgZone, OnInit, ViewChild } from '#angular/core';
import { FormBuilder, FormGroup } from '#angular/forms';
import * as moment from 'moment';
import { interval, Subject, PartialObserver, Observable, Subscriber, of, timer, Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { ReplayService } from 'src/app/Core/services/monitoring/replay.service';
import * as L from 'leaflet';
import 'leaflet.animatedmarker/src/AnimatedMarker'
import * as $ from 'jquery';
import { waitForAsync } from '#angular/core/testing';
#Component({
selector: 'app-replay',
templateUrl: './replay.component.html',
styleUrls: ['./replay.component.css'],
})
export class ReplayComponent implements OnInit {
displayedColumns: any[] = ['startDateTime', 'endDateTime', 'vehicleRegNo'];
newArr: any[] = [];
arrayofLatLng = [];
replayFrom: FormGroup;
map: L.Map;
private centroid: L.LatLngExpression = [13.30153, 79.93975];//13.30153/79.93975
ployLine: any;
route: any;
replayData: any[] = [];
replayRow: any;
nowTabelData:any[]=[];
animatedMarker;
myIcon=L.icon({
iconUrl: '/assets/images/truck.png',
iconSize: [32, 37],
iconAnchor: [16, 37],
popupAnchor: [0, -28]
});
constructor(private formBuilder: FormBuilder, private replayService: ReplayService) {
this.replayFrom = this.formBuilder.group({
startDateTime: ['', ''],
endDateTime: ['', ''],
vehicleRegNo: ['', ''],
})
}
getData(replayFrom: FormGroup) {
console.log(this.replayFrom.value);
let startDateTime = replayFrom.value.startDateTime;
let endDateTime = replayFrom.value.endDateTime;
let vehicleRegNo = replayFrom.value.vehicleRegNo;
let abc = replayFrom.value;
let fromDateFormat = moment(new Date(startDateTime)).format("YYYY-MM-DD HH:mm:ss");
let toDateFormat = moment(new Date(endDateTime)).format("YYYY-MM-DD HH:mm:ss");
this.getReplayData(fromDateFormat, toDateFormat, vehicleRegNo, abc);
}
ngOnInit() {
}
sub: Subscription;
getReplayData(startDateTime: string, endDateTime: string, vehicleRegNo: string, abc: any) {
this.replayService.getReplay(startDateTime, endDateTime, vehicleRegNo, abc)
.subscribe({
next: this.handleReplayResponse.bind(this),
error: this.handleReplayError.bind(this),
});
}
handleReplayResponse(res: any): void {
let tempArr = res.data;
this.replayData = tempArr;
this.myLoop();
}
i=0;
j=10;
k=0;
t=0;
myLoop(){
let letLng=[] ;
setTimeout(()=> {
this.i++;
console.log(this.i);
if (this.i < this.replayData.length) {
console.log(this.replayData.length);
this.myLoop();
console.log(this.replayData[this.i].eventLat);
for(;this.k<this.j;this.k++){
console.log(this.k);
this.nowTabelData.push(this.replayData[this.k]);
const latN = this.replayData[this.k].eventLat;
const lanN = this.replayData[this.k].eventLong;
if (latN > 0 && lanN > 0 && latN!=undefined && lanN!=undefined) {
this.arrayofLatLng.push([latN, lanN]);
letLng.push([latN,lanN]);
}
}
this.i=this.k;
this.k=this.j;
this.j=this.j+10;
}
debugger;
console.log(letLng);
console.log(this.arrayofLatLng);
this.ployLine = new L.Polyline([this.arrayofLatLng], {
weight: 8,
color: 'red'
}).addTo(this.map);
this.animatedMarker=L.animatedMarker(this.arrayofLatLng,{icon:this.myIcon,interval:100,autoStart:false});
this.map.addLayer(this.animatedMarker);
}, 1000);
}
startMarker(){
this.t=0;
this.animatedMarker.start();
}
handleReplayError(err: any) {
console.log(err);
}
private initMap(): void {
this.map = L.map('map', {
center: this.centroid,
zoom: 10
});
const tiles = L.tileLayer('http://3.110.6.95:8070/mapcache/tms/1.0.0/osmindiamap#indiagrid/{z}/{x}/{-y}.png', {
maxZoom: 18,
minZoom: 2,
attribution: '© OpenStreetMap'
})
tiles.addTo(this.map);
}
ngAfterViewInit() {
this.initMap();
}
pauseMarker(){
this.t=1;
this.animatedMarker.stop();
}
}
Related
Hi Every one here
I face problem with fetching data to array but when I put data to array the editor said not defined array
Error Message:
Failed to compile.
src/app/customers/customers-list/customers-list.component.ts:111:14 - error TS2551: Property 'CUSTOMERS' does not exist on type 'CustomersListComponent'. Did you mean 'customers$'?
111 this.CUSTOMERS = posts;
~~~~~~~~~
src/app/customers/customers-list/customers-list.component.ts:64:3
64 customers$: Observable<Customer[]>;
~~~~~~~~~~
'customers$' is declared here.
This is the CODE
import {
Component,
OnInit,
PipeTransform, // table
} from '#angular/core';
import { DecimalPipe } from '#angular/common'; // table
import { FormControl } from '#angular/forms'; // table
import { Observable } from 'rxjs'; // table
import { map, startWith } from 'rxjs/operators'; // table
import {NgbModal} from '#ng-bootstrap/ng-bootstrap'; // modal
import {AddCustomerComponent} from '../add-customer/add-customer.component'; // modal
import { faFolderPlus, faPencilAlt, faTrashAlt } from '#fortawesome/free-solid-svg-icons'; // fontawsome icons
import {HttpClient} from '#angular/common/http';
// table
interface Customer {
id: number;
name: string;
company: string;
remaining: number;
email: string;
mobile: number;
whats_up: number;
}
let CUSTOMERS: Customer[] = [
{
id: 12,
name: 'jack',
company: 'SDTE',
remaining: 580,
email: 'test#test.com',
mobile: +456456456456,
whats_up: +456456456
}
];
function search(text: string, pipe: PipeTransform): Customer[] {
return CUSTOMERS.filter(customer => {
const term = text.toLowerCase();
return customer.name.toLowerCase().includes(term)
|| customer.company.toLowerCase().includes(term)
|| pipe.transform(customer.remaining).includes(term)
|| customer.email.toLowerCase().includes(term)
|| pipe.transform(customer.mobile).includes(term)
|| pipe.transform(customer.whats_up).includes(term);
});
}
#Component({
selector: 'app-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.css'],
providers: [DecimalPipe] // table
})
export class CustomersListComponent implements OnInit {
// table
customers$: Observable<Customer[]>;
filter = new FormControl('');
faFolderPlus = faFolderPlus;
faPencilAlt = faPencilAlt;
faTrashAlt = faTrashAlt;
constructor(
pipe: DecimalPipe, // table
private modalService: NgbModal, // modal
private http: HttpClient // Get All Data
) {
// table
this.customers$ = this.filter.valueChanges.pipe(
startWith(''),
map(text => search(text, pipe))
);
}
ngOnInit(): void {
this.getAllData();
}
// modal
openPopupModal() {
const modalRef = this.modalService.open(AddCustomerComponent,{ centered: true, size: 'lg' });
modalRef.componentInstance.name = 'World';
}
private getAllData() {
this.http
.get('http://localhost:3000/customers')
.subscribe(
posts => {
console.log('GET all Data works');
this.CUSTOMERS = posts; // <<<<< Here is the problem ************ How can I to Fix it.
});
}
}
I
this.CUSTOMERS = posts; this refers to current class CustomersListComponent but your variable is outside the class so you need to assign directly CUSTOMERS = posts; :)
You need to specify the return type.
You could try using this:
private getAllData() {
this.http
.get<Customer[]>('http://localhost:3000/customers') // <<<<< Try using this.
.subscribe(
posts => {
console.log('GET all Data works');
CUSTOMERS = posts;
});
}
I'm trying to do an action after creating an event.
Create a control form that has been selected in form1 several p, and update a PSelected table.
I have two files, A.html and A.ts
A.html:
<mat-select placeholder="form1" [formControl]="product" (ngModelChange)="getP($event)" multiple> <mat-option *ngFor="let p of allProduct" [value]="p.pro_nom">{{p.pro_nom}}</mat-option>
</mat-select>
<mat-form-field *ngFor="let valeurControls of valeursControls">
<input matInput maxLength="255" type="text [placeholder]="valeurControls.valeur.n [formControl]="valeurControls.formControl">
</mat-form-field>
A.ts:
import { ChangeDetectorRef, Component, OnInit, ViewEncapsulation, Output, EventEmitter } from '#angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '#angular/forms';
import { filter, takeUntil } from 'rxjs/operators';
import { Product, Candy } from 'src/app/models';
import { Service } from 'src/app/services';
import { Listener } from 'selenium-webdriver';
#Component({
selector: 'ei',
templateUrl: './A.component.html',
styleUrls: ['./A.component.less'],
encapsulation: ViewEncapsulation.None
})
export class AComponent extends FormFieldsContainer implements OnInit {
#Output('change') inputChange = new EventEmitter();
//var
allProduct: Product[];
Candy: Candy;
// Form
actionFormGroup: FormGroup;
product: FormControl;
event: Listener[]
// P
valeursControls: { valeur: candy, formControl: FormControl }[] = [];
public pSelected: Array<any>;
// Constructor
constructor(private fb: FormBuilder) {
super();
this.Candy = this.Candy ? this.Candy : { name: null, type: null };
this.pSelected = [];
this.buildForm();
}
ngOnInit() {
this.Service.getProduct()
.pipe(takeUntil(this.unsubscribe))
.subscribe(p => {
this.allProduct = p;
});
}
getP(event?: Event[]) {
if (typeof event == 'undefined') {
this.pSelected = [];
} else {
this.pSelected = event;
}
console.log(this.pSelected)
return this.pSelected;
}
getFormGroup(): FormGroup {
return this.actionFormGroup;
}
onSubmitSuccess<Boolean>(result: Boolean) {
}
private buildForm() {
this.submitted = false;
this.p= this.fb.control('', Validators.required);
this.actionFormGroup = this.fb.group({
product: this.product
});
// my array does not update, it remains empty
this.pSelected .forEach(p => {
const VarFormControl = this.fb.control(null);
this.valeursControls.push({
valeur: { name: p, type: this.Candy.type },
formControl: VarFormControl
});
this.actionFormGroup.addControl(p, VarFormControl );
});
}
Actions() {
this.submitted = true;
}
}
in the function getP(), my table is updating, but when I use it in buildForm() it is empty yet it should have the same value
you are calling this.buildForm(); from the component constructor.
The value of pSelected will be the declared one: public pSelected: Array;
You should rebuild valeursControls any time you select/unselect a value inside the mat-select component.
try:
getP(event?: Event[]) {
this.valeursControls = [];
if (typeof event == 'undefined') {
this.pSelected = [];
} else {
this.pSelected = event;
this.buildValeursControls();
}
}
private buildValeursControls(){
this.pSelected.forEach(p => {
const VarFormControl = this.fb.control(null);
this.valeursControls.push({
valeur: { n: p, r: this.B.r },
formControl: VarFormControl
});
this.actionFormGroup.addControl(p, VarFormControl );
});
}
private buildForm() {
this.submitted = false;
this.p= this.fb.control('', Validators.required);
this.actionFormGroup = this.fb.group({
p: this.p
});
}
I have created a mat-table to display list of Jobs.
Now I want to add a mat-filter to search a job using date or JobId.
However the code that I have written doesn't seem to work.
It does not throw any errors and it doesn't filter data.
HTML Code:
<mat-form-field>
<input
matInput
(keyup)="applyFilter($event.target.value)"
placeholder="Search"
/>
</mat-form-field>
<mat-table [dataSource]="jobExecutionList">
...
Typescript Code:
jobExecutionList: any = [];
applyFilter(filterValue: string) {
this.jobExecutionList.filter = filterValue.trim().toLowerCase();
}
Whole Typescript file :
import { Component, OnInit } from "#angular/core";
import { MatTableDataSource } from "#angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak-
bar.component";
import { DataSource } from "#angular/cdk/collections";
import { Observable, of } from "rxjs";
import {
animate,
state,
style,
transition,
trigger
} from "#angular/animations";
import { RecommendationService } from "../recommendation-service.service";
import { MessageService } from '../../services/message.service';
#Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"],
animations: [
trigger("detailExpand", [
state(
"collapsed",
style({ height: "0px", minHeight: "0", visibility: "hidden" })
),
state("expanded", style({ height: "*", visibility: "visible" })),
transition(
"expanded <=> collapsed",
animate("225ms cubic-bezier(0.4, 0.0, 0.2, 1)")
)
])
]
})
export class JobExecutionScreenComponent implements OnInit {
displaySpinner: boolean = false;
jobId: string;
jobExecutionList: any = [];
jobExecStatDisplayedColumns = [
"jobId",
"executionDate",
"previousTimePeriod",
"afterTimePeriod",
"status",
"actions",
"spinner"
];
public selectedElem: any;
projectjobId: any = 1;
jobExecutionStat: any;
executionDate: string = new Date().toISOString().slice(0, 10);
executeJobStop: any;
changeStatus: any;
newStatus: any;
isExpansionDetailRow = (i: number, row: Object) =>
row.hasOwnProperty("detailRow");
expandedElement: any;
constructor(
private dataService: DataService,
public globalAppSateService: GlobalAppSateService,
private snakbar: SnakBarComponent,
private recommendationService: RecommendationService,
private messageService: MessageService
) {}
ngOnInit() {
const project = JSON.parse(this.dataService.getObject("project"));
if (project != null) {
this.globalAppSateService.onMessage(project);
}
// API to get list of Running Jobs
this.recommendationService
.getJobExecutionStatList(this.projectjobId)
.subscribe(data => {
this.jobExecutionList = data;
console.log(this.jobExecutionList);
// this.jobExecutionStat = new ExampleDataSource();
});
}
applyFilter(filterValue: string) {
this.jobExecutionList.filter = filterValue.trim().toLowerCase();
}
stop_exec_job(element) {
if (element.status == "Running" || element.status == "Pending") {
//Api to stop Job Execution
this.recommendationService
.stopJobExecution(element.jobId, "Cancelled")
.subscribe(data => {
this.executeJobStop = data;
//this.changeStatus.push(this.executeJobStop);
// this.newStatus = new ExampleDataSource();
});
this.displaySpinner = false;
element.status = "Cancelled";
this.snakbar.statusBar("Job Execution Stopped", "Sucess");
} else {
this.snakbar.statusBar("Job Failed to start", "Failure");
}
}
// Will need it for mat-progress bar
// stop_exec_job2() {
// this.stop_exec_job(this.selectedElem);
// this.displaySpinner = false;
// }
re_run_job(element) {
if (
element.status == "Cancelled" ||
element.status == "Completed" ||
element.status == "Executed" ||
element.status == "FINISHED"
) {
//Api to Re-Run Job Execution
this.recommendationService
.stopJobExecution(element.jobId, "Running")
.subscribe(data => {
this.executeJobStop = data;
//this.changeStatus.push(this.executeJobStop);
// this.newStatus = new ExampleDataSource();
});
this.displaySpinner = true;
element.status = "Running";
this.snakbar.statusBar("Job Execution Started", "Sucess");
this.messageService.messageReceived$.subscribe(data => {
this.snakbar.statusBar(
'Platform job status - ' + data,
'Info'
);
//this.isLoadingResults = false;
});
} else {
this.snakbar.statusBar("Job Failed to start", "Failure");
}
}
}
export interface Element {
jobId: number;
executionDate: string;
previousTimePeriod: string;
afterTimePeriod: string;
status: string;
}
This is the Whole typescript file.
Based on different comment, you need to do:
dataSource: MatTableDataSource<any>;
And then when you get the data:
this.dataSource = new MatTableDataSource(/** YOUR DATA **/);
In your example:
import { Component, OnInit } from "#angular/core";
import { MatTableDataSource } from "#angular/material";
import { GlobalAppSateService } from "../../services/globalAppSate.service";
import { DataService } from "../../services/data.service";
import { SnakBarComponent } from "../custom-components/snak-bar/snak-
bar.component";
import { DataSource } from "#angular/cdk/collections";
import { Observable, of } from "rxjs";
import {
animate,
state,
style,
transition,
trigger
} from "#angular/animations";
import { RecommendationService } from "../recommendation-service.service";
import { MessageService } from '../../services/message.service';
#Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"],
animations: [
trigger("detailExpand", [
state(
"collapsed",
style({ height: "0px", minHeight: "0", visibility: "hidden" })
),
state("expanded", style({ height: "*", visibility: "visible" })),
transition(
"expanded <=> collapsed",
animate("225ms cubic-bezier(0.4, 0.0, 0.2, 1)")
)
])
]
})
export class JobExecutionScreenComponent implements OnInit {
displaySpinner: boolean = false;
jobId: string;
jobExecutionList: MatTableDataSource<any>;
jobExecStatDisplayedColumns = [
"jobId",
"executionDate",
"previousTimePeriod",
"afterTimePeriod",
"status",
"actions",
"spinner"
];
public selectedElem: any;
projectjobId: any = 1;
jobExecutionStat: any;
executionDate: string = new Date().toISOString().slice(0, 10);
executeJobStop: any;
changeStatus: any;
newStatus: any;
isExpansionDetailRow = (i: number, row: Object) =>
row.hasOwnProperty("detailRow");
expandedElement: any;
constructor(
private dataService: DataService,
public globalAppSateService: GlobalAppSateService,
private snakbar: SnakBarComponent,
private recommendationService: RecommendationService,
private messageService: MessageService
) {}
ngOnInit() {
const project = JSON.parse(this.dataService.getObject("project"));
if (project != null) {
this.globalAppSateService.onMessage(project);
}
// API to get list of Running Jobs
this.recommendationService
.getJobExecutionStatList(this.projectjobId)
.subscribe(data => {
this.jobExecutionList = new MatTableDataSource(data);
console.log(this.jobExecutionList);
// this.jobExecutionStat = new ExampleDataSource();
});
}
applyFilter(filterValue: string) {
this.jobExecutionList.filter = filterValue.trim().toLowerCase();
}
I already have an example for this kind, you can look over this.
Mat-Table-stackblitz
This code throws an error in the method of "populateGridRows()", at the line of “row.setCompuetedProperties();”. The error message is – “ERROR TypeError: row.setCompuetedProperties is not a function”.
I can see all the properties (with data) on the “row” object in the console just before I get the error.
As far as I can understand it is all about mapping the JSON data coming from the server into a class. Please let me know where I have made a mistake. Thanks.
delivery-plan.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from "#angular/core";
import { ActivatedRoute } from "#angular/router";
import { DetailRow, ExcelExportProperties, FilterSettingsModel, Grid, GridComponent, GridLine, PdfExportProperties } from "#syncfusion/ej2-ng-grids";
import { ClickEventArgs } from '#syncfusion/ej2-ng-navigations';
import { UtilService } from "../../../shared/services/util.service";
import { ConditionBasedMaintenanceStatusEnum } from "../../enums";
import { ConditionAssessmentService, IConditionBasedMaintenanceRowModel } from "../../services/conditionassessment.service";
import { DeliveryPlanModel, DeliveryPlanService, IDeliveryPlanModel } from "../../services/delivery-plan.service";
#Component({
encapsulation: ViewEncapsulation.None,
selector: 'app-delivery-plan',
templateUrl: './delivery-plan.component.html',
styleUrls: ['./delivery-plan.component.scss']
})
export class DeliveryplanComponent implements OnInit {
schoolNumber: number;
deliveryPlanItems: DeliveryPlanModel[];
componentVariables: ConditionAssessmentComponentVariables;
gridRows: Array<DeliveryPlanModel>;
#ViewChild("deliveryItemsGrid") deliveryItemsGrid: GridComponent;
progressValue1 = 100;
progressValue2 = 62;
clickedYear = null;
constructor(private route: ActivatedRoute, private svcConditionAssessment: ConditionAssessmentService,
private svcUtil: UtilService, private deliveryPlanService: DeliveryPlanService) {
this.componentVariables = new ConditionAssessmentComponentVariables();
this.gridRows = new Array<DeliveryPlanModel>();
}
ngOnInit() {
this.route.parent.params.subscribe(params => {
this.schoolNumber = parseInt(params["id"]);
});
Grid.Inject(DetailRow);
this.getDeliveryPlanItems();
}
public getDeliveryPlanItems() {
this.deliveryPlanService
.getDeliveryPlanItems(this.schoolNumber.toString()).subscribe(
data => {
if (data) {
this.deliveryPlanItems = data;
this.populateGridRows();
}
}
)
}
public populateGridRows(): void {
if (this.deliveryPlanItems && this.deliveryPlanItems.length) {
for (var i = 0; i < this.deliveryPlanItems.length; i++) {
let row = this.deliveryPlanItems[i];
console.log(row);
row.setCompuetedProperties(); // The Error is associated with this line
this.gridRows.push(row);
}
}
}
delivery-plan.service.ts
import { HttpClient, HttpHeaders, HttpParams } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { Router } from '#angular/router';
import { Observable, Operator } from "rxjs";
import { ErrorsService } from "../../shared/services/errors.service";
import { ConditionBasedMaintenanceStatusEnum } from "../enums";
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
export interface IDeliveryPlanModel {
//Props
type: string;
id: number;
buildingName: string;
location: string;
asset: string;
element: string;
subElement: string;
description: string;
trade: string;
status: number;
statusDisplay: string;
plannedDate: Date;
completedDate: Date;
deferred: boolean;
// methods
setCompuetedProperties(): void;
}
export class DeliveryPlanModel implements IDeliveryPlanModel {
//Props
type: string = null;
id: number = null;
buildingName: string = null;
location: string = null;
asset: string = null;
element: string = null;
subElement: string = null;
description: string = null;
trade: string = null;
status: number = null;
statusDisplay: string = null;
plannedDate: Date = null;
completedDate: Date = null;
deferred: boolean = null;
color: string = null;
// methods
public setCompuetedProperties(): void {
switch (this.status) {
case ConditionBasedMaintenanceStatusEnum.AddedToPlanner:
this.statusDisplay = "Planned";
break;
case ConditionBasedMaintenanceStatusEnum.Deferred:
this.statusDisplay = "Deferred";
break;
case ConditionBasedMaintenanceStatusEnum.Completed:
this.statusDisplay = "Completed";
break;
}
}
}
#Injectable()
export class DeliveryPlanService {
routePrefix: string = "api/deliveryplans";
constructor(private http: HttpClient, private router: Router, private errorsService: ErrorsService) { }
public getDeliveryPlanItems(schoolId: string): Observable<DeliveryPlanModel[]> {
var list = this.http.get<DeliveryPlanModel[]>(this.routePrefix + "/schools/" + schoolId)
.map<DeliveryPlanModel[], DeliveryPlanModel[]>(items => {
return items;
}).catch(error => this.errorsService.handleError(error));
return list;
}
}
I have two unrelated components 'chatter-page' and 'header'. I need to have some data shared and synchronized between these two components. I have created a service to do the same. It's not working. Help
chatter-page.component ts file
import { Component, OnInit } from '#angular/core';
import { HostListener } from '#angular/core';
import { DatePipe } from '#angular/common';
import { DropdownItem } from '../shared/dropdownItem';
import { ChatterCard } from '../shared/chattercard';
import { ChatterService } from '../services/chatter.service';
import { FilterShareService } from '../services/filter-share.service';
#Component({
selector: 'app-chatter-page',
templateUrl: './chatter-page.component.html',
styleUrls: ['./chatter-page.component.scss'],
providers : [FilterShareService]
})
export class ChatterPageComponent implements OnInit {
batchSize : number = 50;
dateFilterDisplayFlag : boolean = false;
filterFlag : boolean;
loaderFlag : boolean;
competitors : string[] = ['Company1','Company2'];
categories : string[] = ['Category1','Category2','Category3'];
chatterCards : ChatterCard[] = [];
fromDatePicker;toDatePicker;
dateDisplayFilter : string;
sourceFilters : Set<string>;
sentimentFilters : Set<string>;
organizationFilters : Set<string>;
categoryFilters : Set<string>;
serviceCallString : string = "";
scrollId : string = "";
sourceDropdown : DropdownItem[] = [
{ icon: "fab fa-facebook-f", name: "Facebook" },
{ icon: "fab fa-twitter", name: "Twitter"}
];
sentimentDropdown : DropdownItem[] = [
{ icon: "far fa-smile", name: "Positive" },
{ icon: "far fa-frown", name: "Negative" },
{ icon: "far fa-meh", name: "Neutral"}
];
competitorDropdown : DropdownItem[] = [];
categoryDropdown : DropdownItem[] = [];
constructor(private datePipe : DatePipe, private chatterService : ChatterService, private filterShareService : FilterShareService) { }
#HostListener("window:scroll", [])
onScroll(): void {
let windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
let body = document.body, html = document.documentElement;
let docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
let windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {
console.log("Bottom reached");
this.addDisplayCards();
}
}
receiveFilterFlag(){
this.filterFlag = !this.filterFlag;
}
sourceFilterEvent(filter){
let filters = this.sourceFilters;
this.sourceFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeSourceFilters(filters);
}
sentimentFilterEvent(filter){
let filters = this.sentimentFilters;
this.sentimentFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeSentimentFilters(filters);
}
orgFilterEvent(filter){
if(!this.organizationFilters.has(filter.toLowerCase())){
let filters = this.organizationFilters;
filters.clear();
filters.add(filter.toLowerCase());
this.filterShareService.changeOrganizationFilters(filters);
}
}
categoryFilterEvent(filter){
let filters = this.categoryFilters;
this.categoryFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeCategoryFilters(filters);
}
fromDateEvent(){
let from = new Date(this.fromDatePicker);
let fromDate = this.datePipe.transform(from, 'yyyy-MM-dd');
this.filterShareService.changeFromDate(fromDate);
this.calculateDateDisplayFilter();
this.dateFilterDisplayFlag = true;
}
toDateEvent(){
let to = new Date(this.toDatePicker);
let toDate = this.datePipe.transform(to, 'yyyy-MM-dd');
this.filterShareService.changetoDate(toDate);
this.calculateDateDisplayFilter();
this.dateFilterDisplayFlag = true;
}
calculateDateDisplayFilter(){
this.dateDisplayFilter = this.fromDatePicker + " to " + this.toDatePicker;
}
defaultDateFilter(){
this.dateSetter(180);
}
yesterdayDateFilter(){
this.dateSetter(1);
this.dateFilterDisplayFlag = true;
}
weekDateFilter(){
this.dateSetter(7);
this.dateFilterDisplayFlag = true;
}
monthDateFilter(){
this.dateSetter(30);
this.dateFilterDisplayFlag = true;
}
dateSetter(num){
let from = new Date();
from.setDate(from.getDate()-num);
let fromDate = this.datePipe.transform(from, 'yyyy-MM-dd');
let toDate = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
this.filterShareService.changeFromDate(fromDate);
this.filterShareService.changetoDate(toDate);
this.calculateDateDisplayFilter();
}
populateDropDowns(){
this.competitors.forEach((competitor) => {
this.competitorDropdown.push({ icon: "", name: competitor});
});
this.categories.forEach((category) => {
this.categoryDropdown.push({ icon: "", name: category});
});
}
ngOnInit() {
this.populateDropDowns();
this.filterShareService.currSourceFilters.subscribe((filters) => this.sourceFilters = filters);
this.filterShareService.currSentimentFilters.subscribe((filters) => this.sentimentFilters = filters);
this.filterShareService.currOrganizationFilters.subscribe((filters) => this.organizationFilters = filters);
this.filterShareService.currCategoryFilters.subscribe((filters) => this.categoryFilters = filters);
if(!(this.fromDatePicker && this.toDatePicker)) this.defaultDateFilter();
this.filterShareService.currFromDate.subscribe((date) => this.fromDatePicker = date);
this.filterShareService.currtoDate.subscribe((date) => this.toDatePicker = date);
this.applyFilters();
}
}
header.component ts file
import { Component, OnInit } from '#angular/core';
import { DatePipe } from '#angular/common';
import { DropdownItem } from '../shared/dropdownItem';
import { FilterShareService } from '../services/filter-share.service';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
providers: [FilterShareService]
})
export class HeaderComponent implements OnInit {
dateFilterDisplayFlag : boolean = false;
filterFlag : boolean;
competitors : string[] = ['Company1','Company2'];
categories : string[] = ['Category1','Category2','Category3'];
fromDatePicker;toDatePicker;
dateDisplayFilter : string;
sourceFilters : Set<string>;
sentimentFilters : Set<string>;
organizationFilters : Set<string>;
categoryFilters : Set<string>;
sourceDropdown : DropdownItem[] = [
{ icon: "fab fa-facebook-f", name: "Facebook" },
{ icon: "fab fa-twitter", name: "Twitter"}
];
sentimentDropdown : DropdownItem[] = [
{ icon: "far fa-smile", name: "Positive" },
{ icon: "far fa-frown", name: "Negative" },
{ icon: "far fa-meh", name: "Neutral"}
];
competitorDropdown : DropdownItem[] = [];
categoryDropdown : DropdownItem[] = [];
constructor(private datePipe : DatePipe, private filterShareService : FilterShareService) { }
receiveFilterFlag(){
this.filterFlag = !this.filterFlag;
}
sourceFilterEvent(filter){
let filters = this.sourceFilters;
this.sourceFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeSourceFilters(filters);
}
sentimentFilterEvent(filter){
let filters = this.sentimentFilters;
this.sentimentFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeSentimentFilters(filters);
}
orgFilterEvent(filter){
if(!this.organizationFilters.has(filter.toLowerCase())){
let filters = this.organizationFilters;
filters.clear();
filters.add(filter.toLowerCase());
this.filterShareService.changeOrganizationFilters(filters);
}
}
categoryFilterEvent(filter){
let filters = this.categoryFilters;
this.categoryFilters.has(filter.toUpperCase())? filters.delete(filter.toUpperCase()) : filters.add(filter.toUpperCase());
this.filterShareService.changeCategoryFilters(filters);
}
fromDateEvent(){
console.log("Inside dash header")
let from = new Date(this.fromDatePicker);
let fromDate = this.datePipe.transform(from, 'yyyy-MM-dd');
this.filterShareService.changeFromDate(fromDate);
this.calculateDateDisplayFilter();
this.dateFilterDisplayFlag = true;
}
toDateEvent(){
let to = new Date(this.toDatePicker);
let toDate = this.datePipe.transform(to, 'yyyy-MM-dd');
this.filterShareService.changetoDate(toDate);
this.calculateDateDisplayFilter();
this.dateFilterDisplayFlag = true;
}
calculateDateDisplayFilter(){
this.dateDisplayFilter = this.fromDatePicker + " to " + this.toDatePicker;
}
defaultDateFilter(){
this.dateSetter(180);
}
yesterdayDateFilter(){
this.dateSetter(1);
this.dateFilterDisplayFlag = true;
}
weekDateFilter(){
this.dateSetter(7);
this.dateFilterDisplayFlag = true;
}
monthDateFilter(){
this.dateSetter(30);
this.dateFilterDisplayFlag = true;
}
dateSetter(num){
let from = new Date();
from.setDate(from.getDate()-num);
let fromDate = this.datePipe.transform(from, 'yyyy-MM-dd');
let toDate = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
this.filterShareService.changeFromDate(fromDate);
this.filterShareService.changetoDate(toDate);
this.calculateDateDisplayFilter();
}
populateDropDowns(){
this.competitors.forEach((competitor) => {
this.competitorDropdown.push({ icon: "", name: competitor});
});
this.categories.forEach((category) => {
this.categoryDropdown.push({ icon: "", name: category});
});
}
ngOnInit() {
this.populateDropDowns();
this.filterShareService.currSourceFilters.subscribe((filters) => this.sourceFilters = filters);
this.filterShareService.currSentimentFilters.subscribe((filters) => this.sentimentFilters = filters);
this.filterShareService.currOrganizationFilters.subscribe((filters) => this.organizationFilters = filters);
this.filterShareService.currCategoryFilters.subscribe((filters) => this.categoryFilters = filters);
if(!(this.fromDatePicker && this.toDatePicker)) this.defaultDateFilter();
this.filterShareService.currFromDate.subscribe((date) => this.fromDatePicker = date);
this.filterShareService.currtoDate.subscribe((date) => this.toDatePicker = date);
}
}
The fromDatePicker and toDatePicker variables, which are supposed to store calues from two date input fields (from date, to date) which are present in both the components. sourceFilters, sentimentFilters, organizationFilters & categoryFilters are sets of strings.
I need to synchronize the fromDatePicker, toDatePicker, sourceFilters, sentimentFilters, organizationFilters & categoryFilters values between both the components always. This is my filter share service
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class FilterShareService {
private sourceFilters = new BehaviorSubject<Set<string>>(new Set<string>());
currSourceFilters = this.sourceFilters.asObservable();
private sentimentFilters = new BehaviorSubject<Set<string>>(new Set<string>());
currSentimentFilters = this.sentimentFilters.asObservable();
private organizationFilters = new BehaviorSubject<Set<string>>(new Set<string>(["vanguard"]));
currOrganizationFilters = this.organizationFilters.asObservable();
private categoryFilters = new BehaviorSubject<Set<string>>(new Set<string>());
currCategoryFilters = this.categoryFilters.asObservable();
private fromDate = new BehaviorSubject<string>("");
currFromDate = this.fromDate.asObservable();
private toDate = new BehaviorSubject<string>("");
currtoDate = this.toDate.asObservable();
constructor() { }
changeFromDate(date: string){
this.fromDate.next(date);
console.log("Inside service");
console.log(this.fromDate);
}
changetoDate(date: string){
this.toDate.next(date);
}
changeSourceFilters(sourceFilters: Set<string>){
this.sourceFilters.next(sourceFilters);
}
changeSentimentFilters(sentimentFilters: Set<string>){
this.sentimentFilters.next(sentimentFilters);
}
changeOrganizationFilters(organizationFilters: Set<string>){
this.organizationFilters.next(organizationFilters);
}
changeCategoryFilters(categoryFilters: Set<string>){
this.categoryFilters.next(categoryFilters);
}
}
What am i doing wrong? Any help is appreciated. TIA
Remove the [provider] from both chatter-page and header component.
import { Component, OnInit } from '#angular/core';
import { HostListener } from '#angular/core';
import { DatePipe } from '#angular/common';
import { DropdownItem } from '../shared/dropdownItem';
import { ChatterCard } from '../shared/chattercard';
#Component({
selector: 'app-chatter-page',
templateUrl: './chatter-page.component.html',
styleUrls: ['./chatter-page.component.scss']
})
export class ChatterPageComponent implements OnInit {
}
and
header-component.ts
import { Component, OnInit } from '#angular/core';
import { DatePipe } from '#angular/common';
import { DropdownItem } from '../shared/dropdownItem';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
}
having providers: [FilterShareService] means you are initiating the service all the time. So HeaderComponent will have a new separate FilterShareService and ChatterPageComponent will have a separate one. That way they can share .
Move it to your app.module.ts like below.
#NgModule({
imports: [
BrowserModule,
],
declarations: [
HeaderComponent ,
ChatterPageComponent
],
providers: [
FilterShareService,
ChatterService
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Now the service will be shared across all the modules under your AppModule.