다음 구성 요소가 있습니다.
nav.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css'],
providers: [ApiService]
})
export class NavComponent implements OnInit {
menus;
id;
constructor(private api: ApiService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParams.subscribe(queryParams => { this.id = queryParams.id });
this.api.getMenus().subscribe(res => {this.menus = res});
this.route.params.subscribe(routeParams => {
this.set_id(routeParams.id)
})
}
set_id(id){
this.id = id
console.log(this.id)
}
}
이 구성 요소에서 메뉴가로드되고 다음 링크에서 오는 route.param에서 변수가 설정됩니다.
nav.component.html
<div *ngFor="let menu of menus; index as id">
<ul>
<li><a routerLink ="content/{{id}}" (click)="set_id(id)">{{menu['course-lesson-name']}}</a></li>
</ul>
</div>
앱은 정상적으로로드되지만 콘텐츠는 한 번만 업데이트됩니다. 단일 메뉴 항목을 클릭하면 콘텐츠가 표시되지만 후속 클릭이 아무 것도로드하지 않는다는 점에서 기능이 손실됩니다. 각 링크에 대해 브라우저에서 URL을 수동으로 조작하면 콘텐츠가 필요에 따라로드되므로 링크에 문제가 있다고 가정합니다. BTW, ID가 필요에 따라 설정되고 콘솔에 로깅되지만 값에 따라 필요에 따라 콘텐츠를 다시로드하지 않습니다.
필요한 경우 라우터는 다음과 같습니다.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContentComponent } from './content/content.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{path: 'content/:id', component: ContentComponent},
{path: '', component: HomeComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
id를 저장하고 content.component.ts에 전달해야 getContent ()가이를 사용하여 응답에서 올바른 콘텐츠 요소를 구문 분석 할 수 있습니다.
content.component.ts
import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { RouterLink, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
providers: [ApiService]
})
export class ContentComponent implements OnInit {
content;
id;
constructor(private api: ApiService, private route: ActivatedRoute) { }
ngOnInit(){
this.route.queryParams.subscribe(queryParams => { this.id = queryParams.id });
this.api.getContent().subscribe((res : any[]) => {this.content = res[this.id]})
this.api.getContent().subscribe((res) => {this.content = res[this.id]})
}
}
예, URL에서 매개 변수가 변경 될 때 구성 요소가 다시로드되지 않기 때문입니다. 각도 GitHub에는 이것에 대해 꽤 길고 열띤 GitHub 문제가 있습니다. 기본적으로 다음을 수행해야합니다.
ActivatedRoute
구성 요소에 주입 ( this._route
아래)queryParams
필요한 작업을 수행하십시오.예:
this._route.queryParams.subscribe( q => {
// Do something...
} );
이 유형에 대해 따르는 일반적인 패턴은 매개 변수가 함수로 변경 될 때 실행해야하는 모든 논리를 캡슐화하는 것입니다. 그런 다음 해당 함수를 실행 ngOnInit
한 다음 바로 아래에서 구독 queryParams
하여 모든 업데이트에 반응 할 수 있습니다 (따라서이를 처리 한 동일한 함수를 호출).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다