Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users

Dashboard
Notifications
Mark all as read
Q&A

How to retain a service's data between components in Angular 8 ?

+3
−0

I would like to maintain a log that is available to several modules in my Angular 8 system. So I created the following service:

@Injectable({
	providedIn: 'root'
})
export class LogService {
	_log: string[] = [];
	
	constructor() {	}
	
	log(labelMsg: string, msg?: string | object) {
		if (msg && typeof msg != 'string')
			msg = JSON.stringify(msg);
		
		msg = msg ? `${labelMsg}: ${msg}` : labelMsg;
		this._log.push(`[${moment().format("DD/MM/YYYY HH:mm:ss.SSS")}] - ${msg}`);
	}
	
	show() {
		if (this._log.length)
			this._log.forEach(l=>console.log(l));
		else 
			console.log('Empty log');
		
	}
}

But the problem is that when I load I inject it on several components, I get a per-component instance. I mean I log things in app-init, MainComponent and AboutComponent. And each time I change components, .show will output "Empty log". I don't want to persist this data. I want it to live only in the frontend.

How can I retain the data between components ?

Edit

Code of component where I used LogService:

(...)
import { LogService } from 'src/app/shared/services/log.service';
(...)

@Component({
	selector: 'app-show-account',
	templateUrl: './show-account.component.html',
	styleUrls: ['./show-account.component.scss']
})
export class ShowAccountComponent implements OnInit {
        (...)
	constructor(
                (... other services)
		private logService: LogService
	) { }

	ngOnInit() {
                (...)
		this.logService.log('Show account');
	        (...)
        }
        (...)
}

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

2 comments

That sounds strange as I see that the service is provided in the root. Can you share the code from a component where you use LogService ? Alexei‭ 11 days ago

Edited the question to include component code. nelson777‭ 11 days ago

1 answer

+3
−0

Found the problem: I wasn't using router in some links and the whole app was restarted.

Why does this post require moderator attention?
You might want to add some details to your flag.

2 comments

Now everything makes sense. Btw - page refreshes are typically noticeable (some flicker). Is this happening in your case? Thanks for posting an answer. Alexei‭ 10 days ago

Yes it was. My mistake. nelson777‭ 10 days ago

Sign up to answer this question »