Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How to retain a service's data between components in Angular 8 ?
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');
(...)
}
(...)
}
1 answer
Found the problem: I wasn't using router in some links and the whole app was restarted.
1 comment thread