У меня есть простой сервис.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class XmlService {
items$: Subject<Item[]> = new Subject<Item[]>();
constructor() {
setTimeout(() => this.items.next([{age: '20'}]), 4000);
}
}
После настройки в app.module.ts
и соответствующих файлах я прихожу к app.component.ts
, который у меня имеет следующую настройку:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private xmlService: XmlService) {
// Try 1. It worked fine
xmlService.items$.subscribe(items => console.log(items));
}
calledFromClick() {
// Try 2. Does not work at all even though the method is clicked
this.xmlService.items$.subscribe(items => console.log(items));
}
}
Есть ли причина, почему попытка 1 сработала, а попытка 2 не сработала?У меня такое ощущение, что этот вопрос является дубликатом другого вопроса, но я не могу найти правильный способ задать этот вопрос.
Рассчитывать на вашу помощь help