我正在尝试使用 jasmine 为 getCurrentNavigation().extras.state 编写单元测试。
为了解决这个问题,我试图监视这个路由器方法。
我的组件文件,
@Component({
selector: 'app-location-list',
templateUrl: './location-list.component.html',
styleUrls: ['./location-list.component.scss']
})
export class LocationListComponent implements OnInit{
locationId;
locationName;
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
if (this.router.getCurrentNavigation().extras.state) {
this.locationId = this.router.getCurrentNavigation().extras.state.locationId;
}
if (this.router.getCurrentNavigation().extras.state) {
this.locationName = this.router.getCurrentNavigation().extras.state.locationName;
}
}
ngOnInit() { }
}
Run Code Online (Sandbox Code Playgroud)
我的规格文件,
describe('LocationListComponent ', () => {
let component: LocationListComponent ;
let fixture: ComponentFixture<LocationListComponent >;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
LocationListComponent
],
providers: []
})
.compileComponents();
}));
beforeEach(() …Run Code Online (Sandbox Code Playgroud) 我想从一个 html 页面使用 routerLink 和 state 路由到另一个页面。使用标记没有问题,在登录页面的 ngOnInit 期间,我可以按预期检索状态。使用标签主页也可以导航,但状态结果未定义。
我怎么了?
登录页面的html
<button routerLink="/home" [state]="navExtra.state">
Go Home Page via button
</button>
<a routerLink="/home" [state]="navExtra.state">Go Home Page via a</a>
Run Code Online (Sandbox Code Playgroud)
登录页面的ts
import { Component, OnInit } from '@angular/core';
import { NavigationExtras } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage implements OnInit {
navExtra: NavigationExtras = {
state: { data: { a: 'a', b: 'b' } }
};
constructor() {}
ngOnInit() {}
}
Run Code Online (Sandbox Code Playgroud)
首页的ts
import { Component, OnInit …Run Code Online (Sandbox Code Playgroud)