각도로 컴포넌트를 새로 고치는 방법
각이 지다구성 요소에서 새로 고침 작업을 수행하는 데 어려움을 겪고 있습니다.
버튼을 클릭해서 라우터의 컴포넌트를 갱신하고 싶습니다.클릭하면 컴포넌트/라우터를 새로 고쳐야 합니다.
는 는 i i는노노 i i i i i.window.location.reload()
★★★★★★★★★★★★★★★★★」location.reload()
네, 이렇게요.아는 사람이 있으면 도와주세요.
조사 후 아래와 같이 코드를 수정한 결과 스크립트가 작동하였습니다.방금 조건을 추가했습니다.
this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this.router.navigate(['Your actualComponent']);
});
페이지 전체를 새로고침하지 않고 동일한 컴포넌트를 새로고침하려면 this.ngOnInit(); 를 사용합니다.
DeleteEmployee(id:number)
{
this.employeeService.deleteEmployee(id)
.subscribe(
(data) =>{
console.log(data);
this.ngOnInit();
}),
err => {
console.log("Error");
}
}
필요한 컴포넌트의 컨스트럭터에 코드를 추가한 것이 도움이 되었습니다.
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this.mySubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
// Trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
}
});
★★★★★★★★★★★★★★★★★★★★★★★unsubscribe
이 mySubscription에서ngOnDestroy()
.
ngOnDestroy() {
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
상세한 것에 대하여는, 다음의 스레드를 참조해 주세요.https://github.com/angular/angular/issues/13831
다행히 Angular 5.1+를 사용하고 있다면 네이티브 지원이 추가되어 더 이상 해킹을 구현할 필요가 없습니다.Router Module 옵션에서 onSameUrlNavigation을 'reload'로 설정하면 됩니다.
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
상세한 것에 대하여는, https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2 를 참조해 주세요.
이것은 조금 틀렸고 나는 이것이 너에게 도움이 될지는 모르겠지만 너는 시도해보았다.
this.ngOnInit();
이것은 기능이기 때문에, 어떠한 코드라도, 리프레쉬와 같이 호출됩니다.
, " "ngOnInit()
컴포넌트에는 이 컴포넌트를 .
reloadCurrentRoute() {
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
명시적 루트를 사용하지 않는 다른 방법:
async reload(url: string): Promise<boolean> {
await this.router.navigateByUrl('.', { skipLocationChange: true });
return this.router.navigateByUrl(url);
}
다음의 순서에 따릅니다.
{onSameUrlNavigation: 'reload'}
.ts에 되어 있습니다.
NgModule({))
[ . forRoot ( , { SameUrl Navigation : ' ) 、 Import: [ Router Module . forRoot ( routes , { onSameUrl Navigation : ' reload ) } ] 、
[Router : [Router Module]
this.router.routeReuseStrategy.shouldReuseRoute = () => false
음음음음음음음음음음음음음음음음음::::
constructor(private router: Router) { this.router.routeReuseStrategy.shouldReuseRoute = () => false; }
- 버튼을 클릭하여 Ajax 서버 호출을 호출하고 서버에서 원하는 데이터를 가져와 TS 파일의 글로벌 변수를 새 데이터로 바꿉니다.
this.router.navigate([/sameRoute]);
sameRoute URL로 .- onClick false를 클릭합니다. 그렇지 않으면 동일한 페이지를 새로고침하는 대신 메인 라우팅 페이지가 나타납니다.
상세한 것에 대하여는, https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2 를 참조해 주세요.
저는 Angular 12를 쓰고 있어요.
이 작업은 해킹을 통해 수행할 수 있습니다. 샘플 컴포넌트로 이동한 다음 새로고침할 컴포넌트를 탐색합니다.
this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
이전 답변에는 다음과 같은 문제가 있습니다.
- ngOnInit() 등의 라이프 사이클 메서드를 직접 호출하지 마십시오.
- 특히 동적으로 로드하는 컴포넌트가 큰 페이지의 작은 일부일 경우 URL로 재내비게이트하는 것은 차선책입니다.
이것은 나에게 효과가 있었다(권장할 수 있는 것인지 최적의 것인지 모르겠다)
- 동적으로 로드되는 컴포넌트에서 ChangeDetectorRef에 공개 참조를 추가합니다.
- 동적으로 로드된 데이터에는 입력 데이터(이 예에서는 태그)가 몇 개 포함되어 있으며, 이 데이터는 이후 업데이트되어 렌더링 문제가 발생하고 있습니다.
@Input()
tags: string[] = [];
constructor(public changeDetector: ChangeDetectorRef )
- 동적 로드를 수행하는 부모 컴포넌트에서 자 컴포넌트를 동적으로 만들고 일부 데이터를 설정한 후 다음과 같이 생성된 인스턴스의 changeDetector.markForCheck()를 호출합니다.
constructor(private vcrf: ViewContainerRef, private cfr: ComponentFactoryResolver, private elementRef: ElementRef) {
}
public loadComponent(): void {
const componentFactory = this.cfr.resolveComponentFactory(TagsListComponent);
const component = this.container.createComponent(componentFactory);
component.instance.tags = /* whatever data we want to pass */;
component.instance.changeDetector.markForCheck();
...
load Component()는 예를 들어 부모 페이지가 부모 컴포넌트의 어떤 위치로 스크롤되면 동적 컴포넌트가 표시되어야 함을 나타내는 커스텀 함수입니다.
내 어플리케이션에는 컴포넌트가 있으며 모든 데이터는 컴포넌트의 컨스트럭터에서 호출하는 API에서 가져옵니다.페이지 데이터를 갱신하는 버튼이 있습니다.버튼을 클릭하면 데이터를 백엔드에 저장하고 데이터를 새로 고칩니다.따라서 내 요건에 따라 컴포넌트를 새로고침/새로고침하는 것은 데이터만 새로고침하는 것입니다.이것도 필요하시면 컴포넌트 컨스트럭터에 기재되어 있는 동일한 코드를 사용하십시오.
.routeReuseStrategy
에서 : 우 from from :
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
router property 'false'로 설정합니다.
this._router.navigated = false;
다음으로 컴포넌트로 이동합니다.
this._router.navigate(['routeToYourComponent'])
그 후 old/default routeReuseStrategy를 복원합니다.
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
이를 통해 서비스를 만들 수도 있습니다.
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
kdo
// reload page hack methode
push(uri: string) {
this.location.replaceState(uri) // force replace and no show change
await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
this.location.replaceState(uri) // replace
}
constructor(private router:Router, private route:ActivatedRoute ) {
}
onReload(){
this.router.navigate(['/servers'],{relativeTo:this.route})
}
이것만 하면 된다: (각9의 경우)
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
constructor(@Inject(DOCUMENT) private document: Document){ }
someMethode(){ this.document.location.reload(); }
html 파일
<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>
ts 파일
getcoursedetails(id)
{
this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this._route.navigate(["course",id]);
});
router.navigate['/path']
합니다.router.navigateByUrl('/path')
reload () { this.ngOnInit(); }
특정 내 를 " " " ( " " " " " " " " " " " " 를 합니다.{onSameUrlNavigation: 'reload'}
효과가 없는 반면this.router.routeReuseStrategy.shouldReuseRoute = () => false
는 동작하지만 라우터의 글로벌 설정을 변경합니다.
해결방법은 원래 라우터 설정을 변수에 저장한 후 문제의 첫 번째 답변에 따라 컴포넌트 컨스트럭터에서 @abhishek-singh로 변경하였습니다.
private routeReuseStrategy:any;
constructor(
private router:Router
) {
this.routeReuseStrategy = this.router.routeReuseStrategy.shouldReuseRoute;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
패스를 종료할 때는 OnDestroy 훅을 사용하여 원래 설정을 다시 매핑합니다.
public ngOnDestroy():void
{
this.router.routeReuseStrategy.shouldReuseRoute = this.routeReuseStrategy;
}
이것은 나에게 효과가 있었다: this.ngOnInit();
private saveRouterStrategyReuseLogic: any;
ngOnInit() {
// Save logic
this.saveRouterStrategyReuseLogic = this.router.routeReuseStrategy.shouldReuseRoute;
this.router.routeReuseStrategy.shouldReuseRoute = (future, curr) => { return false; };
}
ngOnDestroy() {
this.router.routeReuseStrategy.shouldReuseRoute =
this.saveRouterStrategyReuseLogic;
}
Import Activated Route 및 라우터:
import { ActivatedRoute, Router } from '@angular/router';
그런 다음 컨스트럭터에 추가합니다.
constructor(
private route: ActivatedRoute,
private router: Router,
)
그 후 페이지 새로고침을 실행하는 기능에서 다음을 수행합니다.
reloadURL(): void {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate(['./'], {
relativeTo: this.route,
});
}
그런 다음 단순히 현재 컴포넌트를 새로고침합니다.
나는 같은 문제를 찾다가 이것을 발견했다.그리고 스택오버플로우 전반에 걸쳐 유사한/틀림없는 답변이 너무 많다는 것을 알게 되었습니다.
달성하려는 목표에 따라 답이 달라질 수 있습니다.
- 현재 컴포넌트에 API를 새로고침하기만 하면 됩니다(단순 호출과 유사).
init()
다시 기능) - 페이지의 모든 구성 요소를 다시 작성하도록 angular에 지시합니다(스토어에 저장된 서비스와 데이터는 그대로 유지됩니다).
- 각도(라우터 관련 이벤트)에서 가드, 리졸바 등을 다시 로드합니다.
- HTML, CSS 등을 포함한 페이지의 모든 자산을 새로고침합니다(브라우저 갱신).
보다 쉽게 참조할 수 있도록 솔루션을 다음과 같이 요약합니다.
해결책 1: 전화만 하면 된다ngOnInit()
class MyComponent {
ngOnInit() {...}
reinitComponent() {
this.ngOnInit();
}
}
주의:
- 현재 구성 요소의 전체 상태가 새로 고쳐지는 것은 아닙니다. 예를 들어 생성자에 설정된 변수는 변경되지 않습니다.
- 각 라이프 사이클 훅을 명시적으로 호출해서는 안 됩니다.
- 이는 현재 컴포넌트에만 영향을 미칩니다(페이지의 모든 컴포넌트는 아닙니다).
대체 구문: 이 로직을 다른 로직으로 이동합니다.init()
양쪽에서 기능하고 그것을 호출한다.
class MyComponent {
ngOnInit() {
this.init();
}
init() { ... }
reinitComponent() {
this.init();
}
}
해결책 2A: 다른 경로로 경로 변경 후 현재 경로로 돌아가기
import { ActivatedRoute, Router } from '@angular/router';
class MyComponent {
constructor(private route: ActivateRoute, private router: Router) {}
refreshPage() {
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate([], { relativeTo: this.route });
});
}
주의:
- 사용할 수 있는 중간 경로가 있어야 합니다.
- 중간 루트가 원인이 될 수 있습니다.
- 글로벌 루트 주입 서비스 상태를 새로 고치지 않습니다(예를 들어 currentLogged를 저장하는 경우).서비스 내 InUser)
- 중간 경로에 HTML 템플릿이 있는 경우 사용자에게 즉시 표시됩니다.
- 이를 사용하여 각도로 재생성되는 부모 컴포넌트의 수를 제어할 수 있습니다(예를 들어 중간 루트는
../..
하지 않도록 하기 )
솔루션 2B: 각진 사용RouteReuseStrategy.shouldReuseRoute
여기에는 다음 3가지 단계가 필요합니다.스텝 1: 라우터 모듈을 설정할 때onSameUrlNavigation
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: 'reload',
})
]
}
export class MyRoutingModule {}
2단계: QueryParams에 기반한 컴포넌트를 재사용하지 않도록 Angular에서 RouteReuse 전략을 변경합니다.
import { Injectable, NgModule } from '@angular/core';
import { ActivatedRouteSnapshot, BaseRouteReuseStrategy, RouteReuseStrategy, RouterModule } from '@angular/router';
@Injectable({ providedIn: 'root' })
class CustomRouteReuseStrategy extends BaseRouteReuseStrategy {
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return super.shouldReuseRoute(future, curr) && future.queryParams._refreshing !== 'true';
}
}
@NgModule({
providers: [
{
provide: RouteReuseStrategy,
useClass: CustomRouteReuseStrategy,
},
],
imports: [ // This is from Step 1
RouterModule.forRoot(routes, {
onSameUrlNavigation: 'reload',
})
]
}
export class MyRoutingModule {}
스텝 3: 마지막으로 컴포넌트에서 사용
import { ActivatedRouteSnapshot, Router } from '@angular/router';
class MyComponent {
constructor(private router: Router, private route: ActivatedRoute) {}
refreshPage() {
router.navigate([], {
relativeTo: route,
queryParamsHandling: 'merge',
queryParams: { _refreshing: true },
skipLocationChange: true,
});
}
주의:
- 그러면 이 페이지의 모든 구성 요소가 다시 생성됩니다.
해결책 3: angular config를 사용하여 항상 동일한 URL에서 라우터 이벤트를 실행한다.
모듈을 할 때는 " " 를 합니다.onSameUrlNavigation
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: 'reload',
})
]
}
export class MyRoutingModule {}
주의:
- 가드/해결사만 호출합니다.
- 경로의 구성 요소는 동일하게 유지되며 각도가 페이지에 구성 요소를 다시 생성하지 않습니다.
해결책 4: 브라우저 API를 사용하여 페이지를 갱신하도록 브라우저에 지시합니다.
class MyComponent {
refreshBrowserTab() {
window.location.reload();
}
주의:
- CSS, HTML, JS, 이미지, 글꼴 등의 모든 자산을 포함하여 페이지 전체를 새로고침합니다.
대체 구문: DI로 변경할 수 있는 Angular의 위치를 사용하여 테스트 중에 모의할 수 있습니다.
import { Location } from '@angular/common';
class MyComponent {
constructor(private location: Location) {}
refreshBrowserTab() {
this.location.reload();
}
이와 같이 앵글2의 페이지를 리프레시(하드웨이)하는 다른 방법 f5처럼 보인다
import { Location } from '@angular/common';
constructor(private location: Location) {}
pageRefresh() {
location.reload();
}
언급URL : https://stackoverflow.com/questions/47813927/how-to-refresh-a-component-in-angular
'programing' 카테고리의 다른 글
파라미터로서의 Objective-C 패스블록 (0) | 2023.04.24 |
---|---|
어떻게 두 Git 저장소를 병합합니까? (0) | 2023.04.24 |
NSString을 NSDate로 변환(및 다시 되돌림) (0) | 2023.04.24 |
id 대신 instancetype을 사용하는 것이 좋을까요? (0) | 2023.04.19 |
Windows 배치 파일: .bat vs .cmd? (0) | 2023.04.19 |