gpt4 book ai didi

angular - Angular 色服务未被调用

转载 作者:行者123 更新时间:2023-11-28 21:35:54 25 4
gpt4 key购买 nike

您好,我正在尝试为具有可观察对象的组件编写 Angular 代码,但我无法测试广播服务中的 Angular 色服务调用。我收到一条错误消息,指出未调用该服务。我应该如何访问该服务?任何帮助,将不胜感激。谢谢。

这是我的可观察组件:

  ngOnInit(): void {

this.subscription.add(
this.broadcastService.subscribe('msal:acquireTokenSuccess', (payload) => {
// do something here
this.roleService.checkServerEventReviewers().subscribe(res => {
this.userService.userDetails.role = res ? 'Data Steward' : 'Mosaic Consumer';
if (this.isLoggedIn !== true) {
const redirectUri = sessionStorage.getItem('redirectUri');
if (redirectUri !== undefined || redirectUri !== null) {
this.router.navigateByUrl(redirectUri);
}
}
this.isLoggedIn = true;
};

这是我正在尝试的规范文件:

    describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
providers: [WindowService, HttpClient, RoleService, UserService, HttpHandler, BroadcastService, MsalService,
{
provide: MSAL_CONFIG, // MsalService needs config, this provides it.
useFactory: () => ({ // Note this is an arrow fn that returns the config object
redirectUri: window.location.origin + '/',
clientID: mockData.clientID,
}),
}],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
});

it("Role should be Data Steward", fakeAsync (() => {
const fn = 'msal:acquireTokenSuccess';
const subscription = new Subscription();
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
const spyOnBS = spyOn(app.broadcastService,'subscribe');
const roleServiceCall =
spyOn(app.roleService,'checkServerEventReviewers');
app.ngOnInit();
tick();
fixture.whenStable().then(() => {
expect(spyOnBS).toHaveBeenCalled();
expect(roleServiceCall).toHaveBeenCalled();
});
}));

最佳答案

如果您在组件文件而非规范文件中遇到错误,则将其存储到局部变量中并将其与您的 Angular 色服务一起使用

更新后的代码看起来像

ngOnInit(): void {

const that = this; // STORE this into local variable

this.subscription.add(
this.broadcastService.subscribe('msal:acquireTokenSuccess', (payload) => {
...
// USE "that" instead of "this"
that.roleService.checkServerEventReviewers().subscribe(res => {
...
});
});
);

关于angular - Angular 色服务未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com