У меня есть следующее простое однокомпонентное приложение:
nav.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
//vars
url = 'api address';
menus;
content;
id;
constructor(private http: HttpClient) { }
ngOnInit() {
this.getMenus().subscribe(res => {this.menus = res});
}
//this gets the data for the menus
getMenus(){
return this.http.get(this.url);
}
//this get the data for the content
public getContent(): void {
this.http.get(this.url).subscribe((res) => {this.content = res[this.id]}
);
}
//this gets an id from each menu link, assigns the id to this.id and logs the new value of id.
public get_id(id)
{
this.id = id;
console.log(id)
this.getContent()
return this.id
}
}
nav.component. html
//menus
<div *ngFor="let menu of menus; index as id">
<ul>
<li><button (click)="get_id(id)">{{menu['course-lesson-name']}}</button></li>
</ul>
</div>
//content
<div>
<p *ngIf="content">{{content['course-name']}}</p>
</div>
Вот проблема:
nav.component.ts загружает меню и контент из функций, выполняющих вызовы API, и подписывается на каждую из них с помощью этих двух наблюдаемых:
this.getMenus().subscribe(res => {this.menus = res});
this.getContent().subscribe((res) => {this.content = res[this.id]}) //<--notice this.id variable
Функция get_id (id) извлекает номер индекса индекса из каждой ссылки меню, используя (щелчок), и должна принимать значение переменной this.id.
Мне нужен способ запускать следующее при каждом нажатии каждой кнопки и не включаться в ngOnInit ().
this.getContent().subscribe((res) => {this.content = res[this.id]})
В настоящее время this.getContent () загружается один раз ( потому что он находится в ngOnInit) и не будет перезагружаться, когда ему передается новое значение this.id. Он должен запускаться каждый раз, когда также запускается get_id (id), поэтому ему передается новое значение id и отображается правильное содержимое.
В настоящее время все, что происходит относительный идентификатор регистрируется в консоли каждый раз, когда нажимается кнопка.