Answer the question
In order to leave comments, you need to log in
How to remember the value of an Angular variable?
Hello! I'm most likely doing something wrong.
There is a news directory. I receive news from the server in json format. I create subject variables in services, subscribe in components. There is also a component for filtering news by sections. Sections arrive from the server along with the news. Everything is stored in services.
The problem is the following. When I go to the detailed view of the news and go back, for some reason the variables are overwritten, which should contain a list of sections for the filter and the news. And the subscription to Subject variables does not work.
News service code
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { SectionsService } from './sections.service';
@Injectable({
providedIn: 'root',
})
export class NewsService {
item: [] = [];
news: any[] = [];
activeNews = new Subject<any[]>();
constructor(private sectionsService: SectionsService) {
this.sectionsService.activeSection.subscribe(section => {
if (section != "") {
this.activeNews.next(this.news.filter(items => items.name_section === section));
} else {
this.activeNews.next(this.news);
}
})
}
public newsesList(list: []) {
this.item = list;
}
public listItems(items: any) {
this.news = items;
this.sectionsService.getSections(items);
this.activeNews.next(items);
}
}
import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';
@Component({
selector: 'app-news-list',
templateUrl: './news-list.component.html',
styleUrls: ['./news-list.component.scss']
})
export class NewsListComponent implements OnInit {
nameComponent: string= "News list message: ";
newsActive: any[] = [];
colNews: number = 9;
constructor(private newsesService: NewsService) {}
ngOnInit(): void {
this.newsesService.activeNews.subscribe(newses => {
this.newsActive = newses;
})
}
activeElement(item: []): void {
this.newsesService.newsesList(item);
}
addNews(): void {
this.colNews = this.colNews + 9;
}
}
Answer the question
In order to leave comments, you need to log in
For example, I am making such a service to store the state of the current page.
@Injectable({
providedIn: 'root'
})
export class DashboardStateService {
private contentPage = new BehaviorSubject<number>(1);
public changeContentPage(page: number): void {
this.contentPage.next(page);
}
public getContentPage(): number {
return this.contentPage.getValue()
}
}
async ngOnInit() {
this.currentPage = this.dashboardStateService.getContentPage()
}
this.dashboardStateService.changeContentPage(2)
getData() {
return this.http.get(url).pipe(shareReplay())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question