标签: angular16

Angular 升级后生产构建失败 document.documentElement.setAttribute 不是函数

我已将应用程序升级到 Angular 16,升级进展顺利,应用程序按预期运行

但是当我运行 prod build 命令时

ng build --configuration=production
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

Index html generation failed.
document.documentElement.setAttribute is not a function
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个问题,因为我的代码中没有 documentElement.setAttribute

在 angular.json 中将 optimization 和 buildOptimizer 设置为 false 确实有效,但我知道这不是正确的修复方法

任何帮助或建议将不胜感激

javascript typescript angular angular16

13
推荐指数
1
解决办法
2160
查看次数

如何通过构造函数依赖注入在 Angular 16 中使用 CanActivateFn

如何通过 DI 使用 Angular 16 中最新的 CanActivateFn?

最近的 Angular 16 使用函数而不是类来实现 canactivate 功能。这是我下面的代码。如何添加通常位于函数构造函数中的 DI?

CanActivateFn函数代码:

export const authGuard: CanActivateFn = (
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
) => {
  return inject(TokenService).authenticated.pipe(
    take(1),
    map((status) => {
      console.log('auth status: ', status);
      if (!status) {
        return inject(Router).createUrlTree(['/login']);
      }
      return true;
    })
  );
};
Run Code Online (Sandbox Code Playgroud)

路线设置:

const routes: Routes = [
  {
    path: '',
    component: DefaultComponent,
    canActivate: [authGuard],
    children: [
      {
        path: '',
        component: DashboardComponent,
        data: { title: 'My Dashboard' },
      },
]
Run Code Online (Sandbox Code Playgroud)

angular angular-router-guards angular16

9
推荐指数
2
解决办法
2万
查看次数

Angular 16 中的 routerLink 更改

当使用角度<16时,我曾经有这样的路由配置:

{
  path: Section.Security,
  canActivate: [AuthGuard, AccessGuard, AdminGuard],
  children: [
    {
      path: '',
      pathMatch: 'full',
      redirectTo: 'administrators'
    },
    {
      path: '',
      outlet: 'left-menu',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/components/left-menu/left-menu.component').then(m => m.SecurityLeftMenuComponent)
    },
    {
      path: 'administrators',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    },
    {
      path: 'contributors',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    },
    {
      path: 'readers',
      canActivate: [AuthGuard],
      loadComponent: () => import('@app/pages/security/security.page').then(m => m.SecurityHomePage)
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

并且,在 中SecurityLeftMenuComponent,我有指向子路线的简单链接,例如:

<a class="item"
   routerLinkActive="active"
   routerLink="administrators">
   <rn-key name="security::administrators" …
Run Code Online (Sandbox Code Playgroud)

angular-routing angular angular16

7
推荐指数
1
解决办法
3320
查看次数

升级到 Angular 16 中断 Sharepoint 广告: this._history.replaceState 不是函数

我正在升级在 Share Point 办公室内运行的 Angular 应用程序。目前 Angular 应用程序使用的是版本 14,在我升级到 Angular 15 后,它工作正常。但是当我升级到 16 后,我就收到以下错误。

TypeError: this._history.replaceState is not a function
Run Code Online (Sandbox Code Playgroud)

打电话时会发生这种情况

 this.router.navigate(['/path_to_component']);
Run Code Online (Sandbox Code Playgroud)

我在这个 SO 帖子上找到了修复。Office.js 使浏览器历史记录功能无效,破坏历史记录使用情况

<script type="text/javascript">
    // Office js deletes window.history.pushState and window.history.replaceState. Cache them and restore them
    window._historyCache = {
        replaceState: window.history.replaceState,
        pushState: window.history.pushState
    };
</script>

<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>

<script type="text/javascript">
    // Office js deletes window.history.pushState and window.history.replaceState. Restore them
    window.history.replaceState = window._historyCache.replaceState;
    window.history.pushState = window._historyCache.pushState;
</script>
Run Code Online (Sandbox Code Playgroud)

我不确定升级到 Angular 16 后会发生什么问题,尽管它与 office.js 有关

我正在使用相同版本的office.js。

我已经使用了哈希位置策略。任何人都可以帮助我理解这一点。

office-addins angular-ui-router office-js angular angular16

6
推荐指数
1
解决办法
275
查看次数

如果移动到 npm 库,独立组件的注入会失败

我创建了一个简单的角度独立组件,它使用注入令牌进行配置:

export const PERSON_DEFAULT_OPTIONS = new InjectionToken<IPersonDefaults>('...')

export interface IPersonDefaults { ... }

export const providePersonDefaultOptions = (options: IPersonDefaults): Provider => ({
    provide: PERSON_DEFAULT_OPTIONS,
    useValue: options
})

@Component({...})
export class StandaloneComponent {
   readonly #config = inject(PERSON_DEFAULT_OPTIONS, {optional: true})
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的 main.ts 中,我只需调用providePersonDefaultOptions()我的价值观,一切都会很好。

现在我已经将该令牌/接口/组件放入 npm 库中。当我尝试再次运行该应用程序时,出现以下错误:

错误:NG0203:inject() 必须从注入上下文调用,例如构造函数、工厂函数、字段初始值设定项或使用的函数EnvironmentInjector#runInContext

我不明白为什么该代码不能作为 npm 库工作,因为它仍然是一个正在设置的字段初始值设定项。

angular angular-library injection-tokens angular15 angular16

5
推荐指数
1
解决办法
759
查看次数

ngx-virtual-scroll 在 Angular16 更新后不起作用

ngx-virtual-scroll 在 angular16 更新后无法工作,在终端中显示一个错误。

错误是

'VirtualScrollerModule' does not appear to be an NgModule class.
This likely means that the library (ngx-virtual-scroller) which declares VirtualScrollerModule is not compatible with Angular Ivy. Check if a newer 
version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

typescript angular angular16

5
推荐指数
1
解决办法
1752
查看次数

角度信号如何影响 RXJS Observables 以及在这种情况下检测会发生什么变化

我正在尝试在 Angular 应用程序中切换到信号,目前在寻找良好实践方面遇到问题,并且我也经历了(至少对我来说)意外的行为。

这是我的代码片段,由一个 userService 和两个组件组成

export class UserService {
  private user$: Observable<User>;
  private refreshUser$ = new BehaviorSubject<void>(undefined);

  constructor(private readonly http: HttpClient) {}

  getUser(): Observable<User> {
    if (!this.user$) {
      this.user$ = this.refreshUser$.pipe(
        switchMap(() => this.http.get<User>('...')),
        shareReplay(1)
      );
    }
    return this.user$;
  }

  reloadUser(): void {
    this.refreshUser$.next();
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我有组件 A 为用户订阅:

export class aComponent {

 currentUser: User;

  constructor(private readonly userService: UserService) {
    this.userService.getUser().subscribe((user) => {
      this.currentUser = user;
    });
 }
}
Run Code Online (Sandbox Code Playgroud)

我有组件 aChild,它是组件 A 的子组件,也订阅用户并且还可以操作用户。它能够更改/删除用户的地址。在使用信号之前,我会立即更新组件的 currentUser 对象的地址,以便用户可以立即看到结果,并且我会从服务调用“reloadUser()”,以便全局用户是最新的,并且“A Component " 具有正确的值(这可能不是最好的解决方案,因为它会导致另一个 http …

rxjs angular2-changedetection angular angular-signals angular16

5
推荐指数
1
解决办法
1163
查看次数

Angular 16 中的入口组件替换

我已将我的项目更新到 Angular 16。在 中app.module.ts,我有一组名为 的组件entryComponents。但是,entryComponentsAngular 16 中不再提供这些组件。我应该在哪里将这些组件添加到我的项目中:

entryComponents:[
    PayResultDialogComponent,
    MessageBoxComponent
  ],
Run Code Online (Sandbox Code Playgroud)

typescript angular angular16

5
推荐指数
1
解决办法
4797
查看次数

由于角度故事书中的“类型‘serveroptions’不是通用的”,无法在角度项目中运行故事书

我安装了故事书,npx sb init但是当尝试运行故事书时in angular 16出现以下错误。这些错误并不指向项目中的任何特定代码,而是指向节点和角度中的一些随机代码。

\n
\n

变量 'AbortSignal' 的类型必须为 '{ new (): AbortSignal; 原型:AbortSignal;中止(原因?:任何):AbortSignal;超时(毫秒:数字):AbortSignal;}',但这里有类型 '{ new (): AbortSignal; 原型:AbortSignal;}

\n
\n
\n

类型“ServerOptions”不是通用的

\n
\n

这是详细的错误消息:

\n
\nError: node_modules/@types/node/globals.d.ts:72:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'AbortSignal' must be of type '{ new (): AbortSignal; prototype: AbortSignal; abort(reason?: any): AbortSignal; timeout(milliseconds: number): AbortSignal; }', but here has type '{ new (): AbortSignal; prototype: AbortSignal; }'.\n\n72 declare var AbortSignal: {\n               ~~~~~~~~~~~\n\n …
Run Code Online (Sandbox Code Playgroud)

angular storybook angular-storybook angular16

4
推荐指数
1
解决办法
1471
查看次数

Angular 16 Signal更新不更新视图

我正在测试 Angular 16 信号,根据我的理解,当我禁用 zone.js 并调用 signal.update() 时,视图应该更新为新值。它不是。请帮助我理解为什么。

主要.ts

platformBrowserDynamic().bootstrapModule(AppModule, { ngZone: 'noop' })
    .catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

应用程序组件.ts

@Component({
    selector: 'app-root',
    template: '
        <h1>{{ title() }}</h1>
        <button (click)="click()">Change</button>
    ',
})
export class AppComponent {
    title = signal('Hello');

    click(): void {
        this.title.update((value) => value + "!!");
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望单击按钮后,“标题”的值将从“Hello”更新为“Hello!!”。它没有更新。

signals zonejs angular angular16

4
推荐指数
1
解决办法
3016
查看次数

Angular Universal BrowserModule.withServerTransition 已弃用,替代品是什么?

我正在使用 Angular 16.0.0 和 Angular Universal 服务器端渲染,但是当我BrowserModule.withServerTransition在应用程序模块中导入时,它被标记为已弃用,它的替代品是什么?

在此输入图像描述

我的应用程序模块.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatMenuModule} from '@angular/material/menu';
import {MatButtonModule} from '@angular/material/button'
import {MatIconModule} from '@angular/material/icon';
import {MatCardModule} from '@angular/material/card';
import { HomeComponent } from './home/home.component';
import {MatTabsModule} from '@angular/material/tabs';
import { CoursesCardListComponent } from './courses-card-list/courses-card-list.component';
import {CourseComponent} from "./course/course.component";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { MatDialogModule } from "@angular/material/dialog";
import { …
Run Code Online (Sandbox Code Playgroud)

angular-universal angular angular16

4
推荐指数
1
解决办法
3395
查看次数

我如何才能使用手表选项来玩 Jest 跑步者

我正在测试 v16 附带的新实验性 jest runner。( @angular-devkit/build-angular:jest)。

知道如何使用该--watch选项运行吗?

也许还没有准备好。

jestjs angular angular16

2
推荐指数
1
解决办法
282
查看次数

为什么在 Angular 16 中将 Observable 转换为 WritableSignal 会抛出缺少属性的错误

我的组件上有以下简单代码:

import {Component, effect, signal, WritableSignal} from '@angular/core';
import {AppService} from "../app.service";
import {toSignal} from "@angular/core/rxjs-interop";

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  translations: WritableSignal<{data: {}}> = signal({data: []});

  constructor( private appService: AppService) {
    this.translations = toSignal(this.appService.getTranslations());
    effect(() => {
      console.log('translation API:', this.translations());
    });
  }

  changeValue(): void {
    this.translations.set({data: {hello: 'hallo'}})

  }
}
Run Code Online (Sandbox Code Playgroud)

仅供参考:this.appService.getTranslations()返回一个可观察的

我正在尝试 Angular v16 发布的新功能,以及如何将 Observables 转换为 Signals。

我想要对上面的代码做的是,更改 WritableSignal 对象的值并记录更改时的值。

我收到以下错误:

TS2739: Type 'Signal ' is missing the following …
Run Code Online (Sandbox Code Playgroud)

angular angular-signals angular16

2
推荐指数
1
解决办法
2969
查看次数