AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[angular](coding)

Martin Hope
Anurag Nema
Asked: 2025-04-30 14:22:00 +0800 CST

Angular 测试用例失败,错误代码为 NG0203:必须从注入上下文中调用 inject()

  • 6

我正在使用 TestBed 测试一个 Angular 18 独立组件,并在单元测试期间初始化组件时遇到此错误:错误:NG0203:必须从注入上下文(例如构造函数、工厂函数、字段初始化器或与 一起使用的函数)调用 inject() runInInjectionContext。更多信息请访问https://angular.dev/errors/NG0203

以下是该组件的测试用例:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SomeComponent } from './some-component.component';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';

describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;
  let mockRoute: jasmine.SpyObj<ActivatedRoute>;

  beforeEach(async () => {
    mockRoute = jasmine.createSpyObj('ActivatedRoute', ['fragment'], { fragment: of('test-anchor') });

    await TestBed.configureTestingModule({
      imports: [SomeComponent], 
      providers: [{ provide: ActivatedRoute, useValue: mockRoute }],
    }).compileComponents();

    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

组件代码:

import { Component, OnDestroy } from '@angular/core';
import { LibCommonService, PLATFORM_BEHAVIOR_TYPE_ENUM, PreferencesDashboardComponent } from '@pseudoLib/pseudo-common-elements';
import { TranslateModule } from '@ngx-translate/core';
import { ActivatedRoute } from '@angular/router';
import { Subject, takeUntil } from 'rxjs';
import { NgIf } from '@angular/common';
import { DetailsService } from 'src/shared/services/details.service';
import { MEMBER_TYPE_ENUM } from 'src/shared/models/enums/details.enum';

@Component({
  selector: 'app-some',
  standalone: true,
  imports: [TranslateModule, NgIf, PreferencesDashboardComponent],
  templateUrl: './some.component.html',
  styleUrl: './some.component.scss',
})
export class SomeComponent implements OnDestroy {
  private destroy$ = new Subject<void>();

  PLATFORM_BEHAVIOR_TYPE_ENUM = PLATFORM_BEHAVIOR_TYPE_ENUM;

  projectId!: string;

  memberId!: string;

  memberType!: PLATFORM_BEHAVIOR_TYPE_ENUM;

  constructor(
    private activatedRoute: ActivatedRoute,
    private libCommonService: LibCommonService,
    private DetailsService: DetailsService,
  ) {
    this.projectId = this.libCommonService.projectIdBehaviorSub.getValue();
    this.activatedRoute.parent?.params?.pipe(takeUntil(this.destroy$)).subscribe((params) => {
      this.memberId = params.id;
    });
    this.DetailsService.memberDetails$.pipe(takeUntil(this.destroy$)).subscribe(async (memberDetails) => {
      if (memberDetails?.memberType === MEMBER_TYPE_ENUM.PRIMARY) {
        this.memberType = PLATFORM_BEHAVIOR_TYPE_ENUM.PRIMARY_MEMBER;
      } else if (memberDetails?.memberType === MEMBER_TYPE_ENUM.ASSOCIATE) {
        this.memberType = PLATFORM_BEHAVIOR_TYPE_ENUM.ASSOCIATE_MEMBER;
      }
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

如何解决测试环境中的 NG0203: inject() 错误?如有任何关于如何正确配置使用此服务的独立组件测试环境的建议,我们将不胜感激。

Angular 版本: Angular 18

angular
  • 1 个回答
  • 54 Views
Martin Hope
Nathan30
Asked: 2025-04-29 22:55:20 +0800 CST

如果抛出错误,角度请求重复

  • 5

我的请求出现了一些奇怪的行为。如果请求抛出错误,我会自动启动第二个请求。

在此处输入图片描述

以下是我的请求示例:

this.http.post(environment['url'] + '/ws/verifier/documents/list', {}, {headers}).pipe(
    tap((data: any) => {
        ....
    }),
    finalize(() => {
        ....
    }),
    catchError((err: any) => {
        console.debug(err);
        this.notify.handleErrors(err);
        return of(false);
    })
).subscribe();

如果出现错误,我该如何避免这个重复的请求?

谢谢

编辑:我有这个拦截器。如果抛出 401 错误,它用于刷新令牌。但如果是其他错误,请求就会重新发送。有什么解决方案可以避免这种情况吗?

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
        catchError((err: any) => {
            if (err.status === 401) {
                return this.handle401Error(request, next);
            }
            return next.handle(request);
        })
    );
}
angular
  • 1 个回答
  • 55 Views
Martin Hope
Arnab Mukherjee
Asked: 2025-04-29 14:31:16 +0800 CST

在 HttpTestingController 中添加延迟 - Angular 单元测试

  • 5

尝试验证数据库查询的超时,但无法通过 HttpTestingController 实现。

不确定如何设计 UT。在这个设置中,应该在哪里添加超时。

    it('test timeout', () => {

        service.getData('2025-10-12', '2025-10-16').subscribe(
            {
                next: data => {
                    expect(data).not.toBeNull();
                },
                error: error => {
                    expect(error).toBeNull(); // handling all missing keys
                }
            }
        );

        // mocking endpoint - binding
        const response = httpController.expectOne({
            method: 'GET',
            url: RestServerSA.RELEASES_OVERVIEW_RANGE
        });

        // mocking response from endpoint
        response.flush({});
    });
angular
  • 1 个回答
  • 48 Views
Martin Hope
davood beheshti
Asked: 2025-04-28 23:53:47 +0800 CST

错误类型错误:无法读取 primeng MenuModule 中的 null 属性(读取“offsetHeight”)

  • 6

我正在使用MenuModule primeng

Menu 里面的模型是信号类型

并从服务中取出

现在,当调用服务并填充模型时会显示此错误

ERROR TypeError: Cannot read properties of null (reading 'offsetHeight')

//Html代码

<h1 (click)="statusDispacherClick(213 , $event)">
    Status Click
</h1>
<p-menu #menu [model]="listStatusTypes()" [popup]="true" />

//typeScript 代码

  @ViewChild('menu') menu !: Menu;
  listStatusTypes = signal<any[]>([])

  statusDispacherClick(data, event) {
    this.service.getDashboardChangeStatusTypes(data).subscribe(dataService => {
      dataService.map(x => {
        x.label = x.title;
      })
      this.listStatusTypes.set(dataService);
      this.cdRef.detectChanges();
      this.menu.toggle(event);
    })
  }
angular
  • 2 个回答
  • 38 Views
Martin Hope
kibet
Asked: 2025-04-25 15:35:53 +0800 CST

数据未显示在模板上,但已获取数据

  • 6

我尝试使用 rxResource 显示数据。但是,返回的数据始终未定义。然而,检查网络选项卡显示数据确实正在获取,只是我的组件出了点问题。这段代码有什么问题?因为我似乎找不到问题所在。

API 服务

import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { httpResource } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private readonly httpClient = inject(HttpClient);

  public GET<T>(path: string, options?: any) {
    return this.httpClient.get<T>(path, options);
  }

组件文件:

import { Component, inject, signal } from '@angular/core';
import { ApiService } from '@services/api.service';
import { rxResource, toSignal } from '@angular/core/rxjs-interop';
import { distinctUntilChanged, map } from 'rxjs';

@Component({
  selector: 'app-blogs',
  templateUrl: './blogs.component.html',
  styleUrl: './blogs.component.scss'
})
export class BlogsComponent {

  apiService = inject(ApiService)
  query = signal('')

  rxBlog = rxResource({
    request: () => this.query(),
    loader: () =>
    this.apiService.GET(`https://api.nationalize.io/?name=${this.query()}`)
    .pipe(
      distinctUntilChanged(),
      map((blogs) => blogs),
    )
  })

  search(event: Event) {
    const { value } = event.target as HTMLInputElement;
    this.query.set(value);
  }
} 
 

// Template
<p>blogs works!</p>

<input (input)="search($event)" placeholder="Search user..."/>
    
    <br />
    <ul>
      @let error = rxBlog.error();

      @if (error) {
        <p>{{ error }}</p>
      }

      @if (rxBlog.isLoading()) {
        <p>Loading Blogs...</p>
      }

      @for (blog of (rxBlog.value()).country) {
        {{blog.country_id}}
      }
      
    </ul>

Json数据如下:

{
  "count": 22997,
  "name": "steve",
  "country": [
    {
      "country_id": "KE",
      "probability": 0.0728971981962264
    },
  ]
}
angular
  • 1 个回答
  • 48 Views
Martin Hope
bradrice
Asked: 2025-04-24 04:22:19 +0800 CST

如何在 rxjs 中按顺序返回两个 http 请求并在第二次调用中使用第一个请求的数据?

  • 7

我编写了一个 http 函数,它使用 switch map 从一个 http 请求中获取值并将其用作第二个 http 请求中的参数,但是我如何不仅返回最终的 http 请求,还返回第一个 http 请求的数据?

这是我的功能:

      .post<RxObservable<unknown>>(
        `${this.nextApiEndpoint}ProgramReview/GetAssessmentQuestionNumber`,
        body,
        {}
      )
      .pipe(
        switchMap((data) => {
          return this.http.post<any>(
            `${this.nextApiEndpoint}ProgramReview/GetProgramReviewQuestion`,
            { studentId: args.studentId, questionId: data, programReviewId: args.programReviewId },
            {}
          );
        }),
        catchError((err) => {
          return err;
        })
      );
  }

我在组件中订阅了它并从最终的http请求中获取返回数据,但我还想将第一个请求的数据传递给组件中的订阅。

angular
  • 1 个回答
  • 46 Views
Martin Hope
Aleksandra
Asked: 2025-04-22 22:49:53 +0800 CST

Taiga UI v3 > v4 迁移构建问题

  • 6

我从 Taiga UI v3 迁移到了 v4,添加了一些包(使用 yarn),相应地更新了代码,在运行(angular)项目后解决了所有其他错误,但仍然存在这个我不明白的错误:

...
Build at: 2025-04-22T14:47:34.441Z - Hash: fe6fe04f860facf1 - Time: 2234ms

./node_modules/@taiga-ui/kit/fesm2022/taiga-ui-kit-components-input-number.mjs:209:37-68 - Error: export 'maskitoInitialCalibrationPlugin' (imported as 'maskitoInitialCalibrationPlugin') was not found in '@maskito/core' (possible exports: MASKITO_DEFAULT_ELEMENT_PREDICATE, MASKITO_DEFAULT_OPTIONS, Maskito, maskitoPipe, maskitoTransform)

./node_modules/@taiga-ui/kit/fesm2022/taiga-ui-kit-components-input-phone-international.mjs:245:122-153 - Error: export 'maskitoInitialCalibrationPlugin' (imported as 'maskitoInitialCalibrationPlugin') was not found in '@maskito/core' (possible exports: MASKITO_DEFAULT_ELEMENT_PREDICATE, MASKITO_DEFAULT_OPTIONS, Maskito, maskitoPipe, maskitoTransform)

./node_modules/@taiga-ui/legacy/fesm2022/taiga-ui-legacy-components-input-date-time.mjs:372:34-63 - Error: export 'maskitoSelectionChangeHandler' (imported as 'maskitoSelectionChangeHandler') was not found in '@maskito/kit' (possible exports: maskitoAddOnFocusPlugin, maskitoCaretGuard, maskitoDateOptionsGenerator, maskitoDateRangeOptionsGenerator, maskitoDateTimeOptionsGenerator, maskitoEventHandler, maskitoNumberOptionsGenerator, maskitoParseNumber, maskitoPostfixPostprocessorGenerator, maskitoPrefixPostprocessorGenerator, maskitoRejectEvent, maskitoRemoveOnBlurPlugin, maskitoTimeOptionsGenerator, maskitoWithPlaceholder)

./node_modules/@taiga-ui/legacy/fesm2022/taiga-ui-legacy-components-input-number.mjs:314:37-68 - Error: export 'maskitoInitialCalibrationPlugin' (imported as 'maskitoInitialCalibrationPlugin') was not found in '@maskito/core' (possible exports: MASKITO_DEFAULT_ELEMENT_PREDICATE, MASKITO_DEFAULT_OPTIONS, Maskito, maskitoPipe, maskitoTransform)

./node_modules/@taiga-ui/legacy/fesm2022/taiga-ui-legacy-components-input-time.mjs:413:34-63 - Error: export 'maskitoSelectionChangeHandler' (imported as 'maskitoSelectionChangeHandler') was not found in '@maskito/kit' (possible exports: maskitoAddOnFocusPlugin, maskitoCaretGuard, maskitoDateOptionsGenerator, maskitoDateRangeOptionsGenerator, maskitoDateTimeOptionsGenerator, maskitoEventHandler, maskitoNumberOptionsGenerator, maskitoParseNumber, maskitoPostfixPostprocessorGenerator, maskitoPrefixPostprocessorGenerator, maskitoRejectEvent, maskitoRemoveOnBlurPlugin, maskitoTimeOptionsGenerator, maskitoWithPlaceholder)


✖ Failed to compile.

node_modules 中缺少一些包,所以我手动添加了它们,现在只剩下这些错误了。我该怎么办?

以下是 package.json 依赖项目前的样子:

"dependencies": {
    "@angular-builders/custom-webpack": "18.0.0",
    "@angular/animations": "18.2.9",
    "@angular/cdk": "18.2.9",
    "@angular/common": "18.2.9",
    "@angular/compiler": "18.2.9",
    "@angular/core": "18.2.9",
    "@angular/forms": "18.2.9",
    "@angular/platform-browser": "18.2.9",
    "@angular/platform-browser-dynamic": "18.2.9",
    "@angular/router": "18.2.9",
    "@auth0/auth0-angular": "2.2.3",
    "@aws-sdk/client-s3": "3.627.0",
    "@aws-sdk/lib-storage": "3.627.0",
    "@aws-sdk/s3-request-presigner": "3.627.0",
    "@bigchaindb/wallet-hd": "0.4.3",
    "@bigchaindb/wallet-plugins": "0.4.5",
    "@jenniferplusplus/opentelemetry-instrumentation-bullmq": "0.5.0",
    "@maskito/angular": "1.9.0",
    "@maskito/core": "1.9.0",
    "@maskito/kit": "1.9.0",
    "@maskito/phone": "3.7.1",
    "@nestjs/axios": "3.1.3",
    "@nestjs/bullmq": "10.2.3",
    "@nestjs/cache-manager": "2.3.0",
    "@nestjs/common": "10.4.15",
    "@nestjs/config": "3.3.0",
    "@nestjs/core": "10.4.15",
    "@nestjs/event-emitter": "2.1.1",
    "@nestjs/microservices": "10.4.15",
    "@nestjs/passport": "10.0.3",
    "@nestjs/platform-express": "10.4.15",
    "@nestjs/schedule": "3.0.3",
    "@nestjs/swagger": "7.2.0",
    "@nestjs/terminus": "10.2.3",
    "@nestjs/throttler": "4.2.1",
    "@nestjs/typeorm": "10.0.2",
    "@ng-web-apis/common": "4.12.0",
    "@ng-web-apis/intersection-observer": "4.12.0",
    "@ng-web-apis/mutation-observer": "4.12.0",
    "@ng-web-apis/platform": "4.12.0",
    "@ng-web-apis/resize-observer": "4.12.0",
    "@ng-web-apis/screen-orientation": "4.12.0",
    "@ngneat/tailwind": "7.0.3",
    "@ngneat/transloco": "4.3.0",
    "@ngneat/transloco-keys-manager": "3.8.0",
    "@ngneat/transloco-locale": "4.1.0",
    "@ngneat/transloco-persist-lang": "4.0.0",
    "@ngneat/transloco-validator": "3.0.1",
    "@opentelemetry/api": "1.7.0",
    "@opentelemetry/exporter-trace-otlp-grpc": "0.47.0",
    "@opentelemetry/instrumentation-amqplib": "0.33.5",
    "@opentelemetry/instrumentation-aws-sdk": "0.37.2",
    "@opentelemetry/instrumentation-dns": "0.32.5",
    "@opentelemetry/instrumentation-express": "0.34.1",
    "@opentelemetry/instrumentation-generic-pool": "0.32.5",
    "@opentelemetry/instrumentation-http": "0.47.0",
    "@opentelemetry/instrumentation-ioredis": "0.36.1",
    "@opentelemetry/instrumentation-nestjs-core": "0.33.4",
    "@opentelemetry/instrumentation-net": "0.32.5",
    "@opentelemetry/instrumentation-pg": "0.37.2",
    "@opentelemetry/instrumentation-pino": "0.34.5",
    "@opentelemetry/resources": "1.20.0",
    "@opentelemetry/sdk-node": "0.47.0",
    "@opentelemetry/sdk-trace-base": "1.20.0",
    "@opentelemetry/semantic-conventions": "1.20.0",
    "@rx-angular/cdk": "16.0.0",
    "@rx-angular/state": "16.0.0",
    "@rx-angular/template": "16.0.1",
    "@s1seven/cluster-service": "0.15.5",
    "@s1seven/custom-schema-tools-certificate-summary": "0.2.0",
    "@s1seven/custom-schema-tools-extract-emails": "0.1.1",
    "@s1seven/custom-schema-tools-generate-tkr-pdf-template": "0.2.0",
    "@s1seven/custom-schema-tools-types": "0.1.1",
    "@s1seven/nestjs-tools-access-control": "0.1.15",
    "@s1seven/nestjs-tools-amqp-transport": "0.5.1",
    "@s1seven/nestjs-tools-async-local-storage": "0.2.2",
    "@s1seven/nestjs-tools-file-storage": "0.8.0",
    "@s1seven/nestjs-tools-lock": "0.7.0",
    "@s1seven/pino-heroku-pipeline": "0.1.1",
    "@s1seven/schema-tools-validate": "0.3.16",
    "@sendgrid/eventwebhook": "8.0.0",
    "@sendgrid/mail": "8.1.4",
    "@sentry/angular": "7.118.0",
    "@sentry/integrations": "7.118.0",
    "@sentry/node": "7.118.0",
    "@sentry/opentelemetry": "7.118.0",
    "@sentry/profiling-node": "7.118.0",
    "@sentry/types": "7.118.0",
    "@splitbee/web": "0.3.0",
    "@taiga-ui/cdk": "4.32.0",
    "@taiga-ui/core": "4.32.0",
    "@taiga-ui/event-plugins": "4.5.1",
    "@taiga-ui/i18n": "4.32.0",
    "@taiga-ui/icons": "4.32.0",
    "@taiga-ui/kit": "4.32.0",
    "@taiga-ui/layout": "4.32.0",
    "@taiga-ui/legacy": "4.32.0",
    "@taiga-ui/polymorpheus": "4.9.0",
    "@taiga-ui/styles": "4.32.0",
    "@tinkoff/ng-dompurify": "4.0.0",
    "@tinkoff/ng-polymorpheus": "4.3.0",
    "ajv": "8.16.0",
    "ajv-formats": "3.0.1",
    "amqp-connection-manager": "4.1.14",
    "amqplib": "0.10.3",
    "auth0": "4.13.0",
    "axios": "1.7.9",
    "axios-retry": "4.5.0",
    "bigchaindb-driver": "4.3.0",
    "body-parser": "1.20.2",
    "bs58": "5.0.0",
    "bullmq": "4.8.0",
    "cache-manager": "5.3.2",
    "cache-manager-ioredis-yet": "1.2.2",
    "chalk": "4.1.2",
    "class-transformer": "0.5.1",
    "class-validator": "0.14.1",
    "cookie-parser": "1.4.7",
    "country-code-lookup": "0.1.1",
    "date-fns": "2.30.0",
    "dotenv": "16.3.2",
    "dotenv-expand": "10.0.0",
    "express": "4.19.2",
    "express-rate-limit": "7.4.1",
    "handlebars": "4.7.8",
    "helmet": "8.0.0",
    "hyperid": "3.1.1",
    "ioredis": "5.3.2",
    "json-stable-stringify": "1.1.1",
    "jwks-rsa": "3.1.0",
    "lato-font": "3.0.0",
    "lodash": "4.17.21",
    "lodash.clonedeepwith": "4.5.0",
    "loopbench": "2.0.0",
    "lru-cache": "10.1.0",
    "mime": "3.0.0",
    "minimatch": "9.0.3",
    "mqtt": "5.3.6",
    "nestjs-asyncapi": "1.2.1",
    "nestjs-pino": "4.0.0",
    "nestjs-throttler-storage-redis": "0.4.1",
    "nestjs-typeorm-paginate": "4.0.4",
    "node-cache": "5.1.2",
    "otpauth": "9.2.2",
    "papaparse": "5.4.1",
    "passport": "0.7.0",
    "passport-jwt": "4.0.1",
    "pg": "8.11.3",
    "pg-query-stream": "4.5.3",
    "pino": "8.17.2",
    "pino-datadog-transport": "1.3.2",
    "pino-http": "9.0.0",
    "pino-pretty": "10.3.1",
    "qrcode": "1.5.3",
    "query-string": "7.1.3",
    "reflect-metadata": "0.2.1",
    "rxjs": "7.8.1",
    "semver": "7.5.4",
    "semver-lite": "0.0.6",
    "swagger-ui-express": "5.0.0",
    "tar": "6.2.1",
    "ts-mixer": "6.0.4",
    "tslib": "2.6.2",
    "tweetnacl-util": "0.15.1",
    "typeorm": "0.3.19",
    "typeorm-encrypted": "0.8.0",
    "zone.js": "0.14.10"
  },
angular
  • 1 个回答
  • 34 Views
Martin Hope
Zed
Asked: 2025-04-22 20:44:26 +0800 CST

用户刷新页面时 Angular 中的 patchValue 和异步信号出现问题

  • 7

我正在使用 Angular 的新信号功能来管理表单中的反应状态。

大多数情况下一切正常。但是,我遇到了一个问题:

当用户在表单上刷新页面时,组件会重新加载。表单所需的数据会被异步获取,并通过 暴露出来Signal。但表单在信号获取值之前就已经初始化了。

因此,当我调用form.patchValue(...)during 时ngOnInit,信号的值仍然是undefined。

我还考虑过使用 effect() 在信号改变时主动更新表单,但根据 Angular 文档,effect() 并不适用于这种逻辑。


// user userApplication Component
  get customer(): Signal<Customer | null> {
    return this._store.customer;
  }

// form Component

ngOnInit(): void {
    const customer = this.userApplication.customer();
    if (customer && customer.identity) {
      const identity = customer.identity;
      this.identity.patchValue({
        title: identity.title,
        firstName: identity.firstName,

      });
    }
  }

  

  identity = inject(FormBuilder).group({
    title: new FormControl<string | null>(null),
    firstName: new FormControl<string>('', [Validators.required]),
   
  });
angular
  • 1 个回答
  • 45 Views
Martin Hope
derstauner
Asked: 2025-04-22 17:08:46 +0800 CST

尽管设置正确,但仍出现“检查后表达式已更改”错误

  • 5

我遇到了这个错误expression has changed after it was checked。我知道这个检查只在开发模式下运行(运行两次),并且在生产模式下不会出现这个错误信息。但我想知道为什么会这样。

我有一个基于信号的加载器服务,如下所示:

import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoaderService {
  private _isLoading = signal<boolean>(false);

  get isLoading(): boolean {
    return this._isLoading();
  }

  show() {
    this._isLoading.update(() => true);
  }

  hide() {
    this._isLoading.update(() => false);
  }
}

我也有这个拦截器:

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, catchError, map, throwError } from 'rxjs';
import { USE_LOADING_SPINNER } from '../constants/app.constants';
import { LoaderService } from '../../shared/services/loader.service';

@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
  constructor(private loaderService: LoaderService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.context.get(USE_LOADING_SPINNER)) this.loaderService.show();

    return next.handle(req).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) this.loaderService.hide();
        return event;
      }),
      catchError((error) => {
        this.loaderService.hide();
        return throwError(() => error);
      })
    );
  }
}

始终设置USE_LOADING_SPINNER为 true,这意味着我只需标记那些我不想有任何加载指示器的请求。

由于LoaderService是基于信号的,因此我effect在组件的构造函数中注册了一个,如下所示:

constructor() {
    effect(() => {
      this.loading = this.loaderService.isLoading;
    });
  }

请注意,该loading变量不是信号,而是一个纯布尔变量,因为该isLoading方法返回布尔值,而不是信号。

在模板中,我在网格组件中有这个:

[loading]="loading"

此设置正在运行,初始路由时会显示加载指示器。

现在我向组件添加一个刷新方法,如下所示:

refresh() {
    //this.loaderService.show();
    this.gridData$ = this.userService.getUsers();
    //.pipe(tap(() => this.loaderService.hide()));
  }

但是,如果我点击刷新,主题标题就会报错,而且加载指示器也没有显示。拦截器被触发了,我检查了一下。

但如果我取消注释对它的调用,loaderService它就会按预期工作。

为什么我会收到这个错误?

angular
  • 2 个回答
  • 64 Views
Martin Hope
Otto Abnormalverbraucher
Asked: 2025-04-22 08:04:26 +0800 CST

如何在 toSignal 中将空数组设置为默认值?

  • 5

我有一个 DataHandler 服务,它调用数据库服务并将值返回给调用组件。数据库服务返回一个数组的可观察对象,而我希望数据处理程序返回一个可供组件使用的相同数组的信号。因此,我尝试使用 Angular 的 toSignal 函数,但当我将一个空数组设置为初始值时,我收到以下错误:

Type 'never[]' is not assignable to type 'undefined'.

据我了解,TypeScript 找不到空数组的类型,因此它尝试将数组的类型设置为上述类型never[]。但是,我定义了两次该类型,在数据处理程序的函数调用中,返回类型定义为:

public readOverview(type: DataType): Observable<DataEntry[]> { ... }

因此返回的 Observable 类型是 DataEntry[]。这个类型也是我在数据处理程序中调用 toSignal 函数时专门设置的:

return toSignal<DataEntry[]>(this._dbFacade.readOverview(type), { initialValue: [] });

在我看来,TypeScript 应该能够找到空的初始数组的 DataEntry[] 类型。然而,它却找不到。那么,我该怎么做才能让它找到正确的类型,并能够使用空数组作为初始值呢?

angular
  • 1 个回答
  • 59 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve