标签: angular-lifecycle-hooks

如何在angular2中再次调用ngOnInit()

请在此代码中解释,

当我调用另一个方法时,如何再次调用ngOnInit()

 ngOnInit(): void {
      this.route.params.subscribe((params: Params) => {
        this.model=this.userData;
  });      
 }         

 update() {
        this.loading = true;
        this.userService.update(this.model)
            .subscribe(
                data => {
                    alert ('Update successful');
                },
                error => {
                    alert  ('Not updated');
                    this.loading = false;
                });
                this.user_data();
    }
Run Code Online (Sandbox Code Playgroud)

angular angular-lifecycle-hooks

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

Angular2 - ngAfterViewChecked被多次调用..如何在DOM完全加载后调用一次方法?

我需要jqueryAngular2使用时将插件应用于单选按钮Typescript.

如果我指定了ngAfterViewChecked,则会多次调用它,并且控件会多次刷新.

在DOM准备好之后调用javascript方法的替代解决方案是什么?

angular angular-lifecycle-hooks

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

ngOnInit(),ngAfterViewInit(),ngafterContentInit(),ngAfterViewChecked()和构造函数()之间有什么区别?

ngOnInit(),ngAfterViewInit(),ngafterContentInit(),ngAfterViewChecked()和构造函数()之间有什么区别?我们如何在Angular 2中实现它们?他们的目的和用途是什么?实施它们的所有方面都有用吗?

谢谢.

typescript angular angular-lifecycle-hooks

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

Angular - HTTP 拦截器和配置加载到 APP_INITIALIZE

我有一个带有工厂的配置模块,在应用程序初始化时执行(APP_INITIALIZER)

export function ConfigFactory(config: ConfigService) {
    const res = () => config.load();
    return res;
}
...
{
     provide: APP_INITIALIZER,
     useFactory: ConfigFactory,
     deps: [ConfigService],
     multi: true
}
Run Code Online (Sandbox Code Playgroud)

如果我在页面/组件上打印数据,一切正常。

问题是当我尝试在从 HttpInterceptor 调用的服务中使用配置时:

    {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptor,
        multi: true
    },
Run Code Online (Sandbox Code Playgroud)

拦截器:

constructor(private authenticationService: AuthenticationService) {}
  intercept(request: HttpRequest<any> , next: HttpHandler): Observable<HttpEvent<any>> {

    this.authenticationService.getAccessToken().subscribe((token: string) => { this.accessToken = token.toString(); });
      this.authenticationService.getCurrentUser().subscribe((currentU: string) => { this.currentUser = currentU.toString(); });
    if (this.accessToken)  {
        request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${this.accessToken}`,
            actor: this.currentUser,
    // …
Run Code Online (Sandbox Code Playgroud)

configuration angular-http-interceptors angular angular-lifecycle-hooks

9
推荐指数
1
解决办法
3678
查看次数

如何初始化@Input?

我尝试这样做:

  @Input() data: any[] = [];
Run Code Online (Sandbox Code Playgroud)

在 ngOnInit 里面我看到undefined

 ngOnInit() {
    console.log(this.data);
  }
Run Code Online (Sandbox Code Playgroud)

因此,当我尝试获取长度时,在下面的代码中出现错误:return this.data.length;

因为它是未定义的。

为什么默认情况下初始化不起作用?

@Input() data: any[] = [];
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-lifecycle-hooks

9
推荐指数
1
解决办法
8442
查看次数

离子4:ngOnInit与ionViewWillEnter

使用Ionic 4创建混合应用程序时,最好使用Angular Lifecycle Hook或Ionic Lifecycle Hook专门用于初始化?

角生命周期挂钩-ngOnInit

ngOnInit() {
    this.getData();
}
Run Code Online (Sandbox Code Playgroud)

离子生命周期挂钩-ionViewWillEnter

ionViewWillEnter() {
    this.getData();
}
Run Code Online (Sandbox Code Playgroud)

ionic-framework angular ionic4 angular-lifecycle-hooks

6
推荐指数
3
解决办法
7975
查看次数

动态组件上未调用 ngOnInit

我在一个项目中使用 Angular 8,并且在启动动态组件时遇到问题,因为 ngOnInit 没有被调用。我构建了一个名为 PlaceholderDirective 的指令,如下所示:

@Directive({
  selector: '[appPlaceholder]'
})
export class PlaceholderDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}
Run Code Online (Sandbox Code Playgroud)

并在 ng-template 上使用该指令:

<ng-template appPlaceholder></ng-template>
Run Code Online (Sandbox Code Playgroud)

保存 ng-template 所在 HTML 的组件启动动态组件,如下所示:

@ViewChild(PlaceholderDirective, {static: false}) private placeholder: PlaceholderDirective;
...
constructor(private componentResolver: ComponentFactoryResolver) {}
...
public launchSensorEditComponent(id: number) {
    const componentFactory = this.componentResolver.resolveComponentFactory(SensorEditComponent);
    const hostViewContainerRef = this.placeholder.viewContainerRef;
    hostViewContainerRef.clear();
    const sensorEditComponentRef = hostViewContainerRef.createComponent(componentFactory);
    sensorEditComponentRef.instance.sensorId = id;
}
Run Code Online (Sandbox Code Playgroud)

实际的动态组件非常简单,它注册在AppModule的entryComponents部分中。我已将其范围缩小到最低限度,以便了解问题所在:

@Component({
  selector: 'app-sensor-edit',
  templateUrl: './sensor-edit.component.html',
  styleUrls: ['./sensor-edit.component.css']
})
export class SensorEditComponent implements OnInit {
  @Input() sensorId: …
Run Code Online (Sandbox Code Playgroud)

angular-components angular angular-dynamic-components angular-lifecycle-hooks

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

如何在组件销毁时延迟“ngondestroy”钩子调用?

我想延迟ngOndestroy钩子调用,因为我面临一个问题,即我创建了角度应用程序,因为我使用了动画。

示例 - https://stackblitz.com/edit/angular-iribr7-zorjpc?file=app.component.html

当我按下toggl按钮时,我的组件会显示动画。当我第二次按下该按钮时,我的组件在动画之前被破坏。

在我的组件ngOndestroyhooka 中,我在下面使用了:

    ComponentBase.prototype.ngOnDestroy = function () {
        /* istanbul ignore else  */
        if (typeof window !== 'undefined' && this.element.classList.contains('e-control')) { 
        /* used to delete DOM element to avoid memory leak */
            this.destroy(); 
        /* used to delete template refrences to avoid memory leak */
            this.clearTemplate(null);  ------> used 
        }
    };
Run Code Online (Sandbox Code Playgroud)

我也尝试过settimeout方法,虽然setTimout在调试时使用它可以正常工作,但又没有出现同样的问题

我期待任何其他解决方法或建议来解决这个问题.....

我试过如下,但我没有运气----------

https://stackblitz.com/edit/angular-iribr7-bxvnwg?file=app.component.html

javascript angular-directive angular angular-lifecycle-hooks

5
推荐指数
0
解决办法
490
查看次数

Angular 在 postMessage 的新窗口中没有检测到 ngFor 的变化

背景:单击按钮后,我的主页会打开项目中另一个模块的外部窗口(相同来源)。我还设置了一个 BroadcastChannel 以便这两个窗口现在可以通信。现在,如果此窗口已打开并且用户再次单击触发按钮,我想将此信息传达给窗口:

onAddNewFieldClick() {
    if (this.window === null) {
      this.window = window.open(window.location.origin + '/wizard', 'Field Wizard', 'resizable,scrollbar');
      this.channel = new BroadcastChannel('edit-spec-wizard-channel');
    } else {
      this.channel.postMessage(1);
    }
  }
Run Code Online (Sandbox Code Playgroud)

新窗口侦听此通道并将消息数据附加到 ngFor 中使用的数组。为了更加安全。每次推送新值以导致重新绑定时,我都会继续创建一个全新的数组。这是在新窗口中为组件供电的逻辑。

export class EntryComponent implements OnInit, OnDestroy {

  newFieldChannel: BroadcastChannel;
  newFields: number[] = [];
  constructor() { }

  ngOnInit() {
    this.newFieldChannel = new BroadcastChannel('edit-spec-wizard-channel');
    this.newFieldChannel.onmessage = this.newFieldChannelOnMessage.bind(this);
    this.newFields.push(1);
  }

  func() {
    this.newFields.push(1);
    this.newFields = this.newFields.slice();
  }

  private newFieldChannelOnMessage(event: MessageEvent) {
    this.newFields.push(event.data as number);
    this.newFields = this.newFields.slice();
  }

  ngOnDestroy() {
    this.newFieldChannel.close();
  } …
Run Code Online (Sandbox Code Playgroud)

javascript angular angular-lifecycle-hooks angular8

3
推荐指数
1
解决办法
345
查看次数

Angular - 避免 setTimeout() hack 来获取 div 宽度

编写了一个 Angular 13 组件,每当窗口大小调整时,它都会在 div 中绘制一些内容。

问题是获取 div 的渲染宽度。如果我不使用 setTimeout() 并延迟 170 毫秒,this.treemap.nativeElement.offsetWidth则为零。

由于树形图必须在每次调整窗口大小时重新渲染,我还尝试从 ngAfterViewInit() 调度窗口调整大小事件,但它似乎也发生得太快(所以再次this.treemap.nativeElement.offsetWidth为零)。

模板的相关部分...

  <div #treemap class="treemap col-12"></div>
Run Code Online (Sandbox Code Playgroud)

和缩写代码...

// Details omitted for brevity
export class TreemapComponent implements AfterViewInit {
  @ViewChild('treemap') treemap!: ElementRef

  @HostListener('window:resize', ['$event'])
  private render() {
    const width = this.treemap.nativeElement.offsetWidth
    // code that successfully renders a treemap in the div as long as width != 0
  }

  callHack(): void {
    setTimeout(() => this.render(), 170) // testing shows 170ms is lowest possible …
Run Code Online (Sandbox Code Playgroud)

dom event-handling dom-events angular angular-lifecycle-hooks

3
推荐指数
1
解决办法
857
查看次数