각도 2에서 다시로드하지 않고 경로 매개 변수 변경
앵귤러 2, 구글 맵 등을 사용하여 부동산 웹 사이트를 만들고 있는데, 사용자가지도의 중심을 변경하면지도의 현재 위치와 반경을 나타내는 API를 검색합니다. 문제는 전체 페이지를 다시로드하지 않고 URL에 해당 값을 반영하고 싶습니다. 가능합니까? AngularJS 1.x를 사용하는 몇 가지 솔루션을 찾았지만 각도 2에 대해서는 아무것도 찾지 못했습니다.
당신은 사용할 수 있습니다 location.go(url)
기본적으로 응용 프로그램의 경로에 변화없이, 당신의 URL을 변경 것이다.
참고 이것은 현재 경로에서 자식 경로로 리디렉션과 같은 다른 효과를 유발할 수 있습니다.
설명하는 관련 질문location.go
은Router
변경 사항이 발생하지 않습니다.
RC6부터 상태를 변경하지 않고 URL을 변경하여 경로 기록을 유지하려면 다음을 수행 할 수 있습니다.
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
// If you dont import this angular will import the wrong "Location"
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
constructor( private location: Location )
{}
ngOnInit()
{
this.location.replaceState("/some/newstate/");
}
}
사용하는 location.go(url)
것이 방법이지만 url을 하드 코딩하는 대신을 사용하여 생성하는 것이 router.createUrlTree()
좋습니다.
다음 라우터 호출을 수행하려는 this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute})
경우 구성 요소를 다시로드하지 않고 다음과 같이 다시 작성할 수 있습니다.
const url = this
.router
.createUrlTree([{param: 1}], {relativeTo: this.activatedRoute})
.toString();
this.location.go(url);
angular2의 RCx 릴리스에서이 작업을 수행하는 데 큰 문제가있었습니다. Location 패키지가 이동되었으며 constructor () 내부에서 location.go () 실행이 작동하지 않습니다. 수명주기에서 ngOnInit () 이상이어야합니다. 다음은 몇 가지 예제 코드입니다.
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
constructor( private location: Location )
{}
ngOnInit()
{
this.location.go( '/example;example_param=917' );
}
}
문제에 대한 각 리소스는 다음과 같습니다. https://angular.io/docs/ts/latest/api/common/index/Location-class.html https://angular.io/docs/ts/latest/api/ common / index / LocationStrategy-class.html
For anyone like me finding this question the following might be useful.
I had a similar problem and initially tried using location.go and location.replaceState as suggested in other answers here. However I ran into problems when I had to navigate to another page on the app because the navigation was relative to the current route and the current route wasn't being updated by location.go or location.replaceState (the router doesn't know anything about what these do to the URL)
In essence I needed a solution that DIDN'T reload the page/component when the route parameter changed but DID update the route state internally.
I ended up using query parameters. You can find more about it here: https://angular-2-training-book.rangle.io/handout/routing/query_params.html
So if you need to do something like save an order and get an order ID you can update your page URL like shown below. Updating a centre location and related data on a map would be similar
// let's say we're saving an order. Initally the URL is just blah/orders
save(orderId) {
// [Here we would call back-end to save the order in the database]
this.router.navigate(['orders'], { queryParams: { id: orderId } });
// now the URL is blah/orders?id:1234. We don't reload the orders
// page or component so get desired behaviour of not seeing any
// flickers or resetting the page.
}
and you keep track of it within the ngOnInit method like:
ngOnInit() {
this.orderId = this.route
.queryParamMap
.map(params => params.get('id') || null);
// orderID is up-to-date with what is saved in database now, or if
// nothing is saved and hence no id query paramter the orderId variable
// is simply null.
// [You can load the order here from its ID if this suits your design]
}
If you need to go direct to the order page with a new (unsaved) order you can do:
this.router.navigate(['orders']);
Or if you need to go direct to the order page for an existing (saved) order you can do:
this.router.navigate(['orders'], { queryParams: { id: '1234' } });
I use this way to get it:
const queryParamsObj = {foo: 1, bar: 2, andThis: 'text'};
this.location.replaceState(
this.router.createUrlTree(
[this.locationStrategy.path().split('?')[0]], // Get uri
{queryParams: queryParamsObj} // Pass all parameters inside queryParamsObj
).toString()
);
-- EDIT --
I think that I should add some more informations for this.
If you use this.location.replaceState()
router of your application is not updated, so if you use router information later it's not equal for this in your browser. For example if you use localizeService
to change language, after switch language your application back to last URL where you was before change it with this.location.replaceState()
.
If you don't want this behaviour you can chose different method for update URL, like:
this.router.navigate(
[this.locationStrategy.path().split('?')[0]],
{queryParams: queryParamsObj}
);
In this option your browser also doesn't refresh but your URL
change is also injected into Router
of your application, so when you switch language you don't have problem like in this.location.replaceState()
.
Of course you can choose method for your needs. The first is more lighter because you don't engage your application more than change URL
in browser.
For me it was actually a mix of both with Angular 4.4.5.
Using router.navigate kept destroying my url by not respecting the realtiveTo: activatedRoute part.
I've ended up with:
this._location.go(this._router.createUrlTree([this._router.url], { queryParams: { profile: value.id } }).toString())
참고URL : https://stackoverflow.com/questions/35618463/change-route-params-without-reloading-in-angular-2
'developer tip' 카테고리의 다른 글
익명 함수 속기 (0) | 2020.09.18 |
---|---|
"이 작업을 수행하는 동안 오류가 발생했습니다." (0) | 2020.09.18 |
Java 비교 두 목록 (0) | 2020.09.18 |
코드 우선 DbContext에 연결 문자열 전달 (0) | 2020.09.18 |
데이터베이스 / 모델에서 개체를 제거 할 때 Django 관리자가 파일을 삭제하도록하려면 어떻게해야합니까? (0) | 2020.09.18 |