Trying to update a HTML element between components use an angular service doesn't seem to work for me.
This is not a duplication of How do I return the response from an asynchronous call?.
Full project: https://github.com/flamusdiu/micro-blog/tree/dev
I have this service:
import { ElementRef, Injectable } from '@angular/core';
import { MdSidenav } from '@angular/material';
import { AsyncSubject } from 'rxjs/AsyncSubject ';
import { Article } from '../models/article';
@Injectable ()
export class InterModuleService {
private _article: AsyncSubject <Article> = new AsyncSubject();
public sidenav: MdSidenav;
public sidenavToc: ElementRef;
}
I have placed my observable here. The observable is filled through an Angular Resolver for my route. The component is setup as:
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Article } from '../../models/article';
import { InterModuleService } from '../../service/inter-module.service';
@Component({
selector: 'app-article-detail',
templateUrl: './article-detail.component.html',
styleUrls: ['./article-detail.component.css']
})
export class ArticleDetailComponent implements OnInit {
private article: Article;
constructor( private route: ActivatedRoute, private interModuleService: InterModuleService ) { }
ngOnInit(): void {
this.route.data
.subscribe((data: { article: Article } ) => {
this.interModuleService.article.next(data.article);
});
this.interModuleService.article
.subscribe((data) => {
this.article = data;
this.interModuleService.sidenavToc.nativeElement['innerHTML'] = data.toc;
});
}
}
I get this is some sort of Async problem. I get the article data which updates the view just find. However, any property of the article object is always "undefined" or "null" when read at any point which makes me thing my method of trying to do this is not completely right.
If I add some console.logs like this:
this.interModuleService.article.take(1)
.subscribe((data) => {
this.article = data;
console.log(this.article);
console.log(this.article.toc);
this.interModuleService.sidenavToc.nativeElement['innerHTML'] = data.toc;
});
I get the follow screenshot (ignore the HTML formatting issues):
Just for reference: article.toc
is shorthand for article.attachments['toc']['data']
. However, referencing this directly yields the same result as above. article.attachments['toc']
has data but the property data
is undefined when called.
Changed from BehaviorSubject
to AsyncSubject
since I only really care about the last one emitted. Probably should not expose the Subject but didn't see a good way to not do that. Though data.toc
is still undefined. =(