相关疑难解决方法(0)

Angular 2组件构造函数与OnInit

如果我希望每次加载组件时都会发生函数x,无论是第一次加载,我都会导航到另一个站点并导航回来,或者是组件第五次加载.

我应该把函数x放入什么?组件构造函数还是OnInit?

constructor ngoninit angular

90
推荐指数
3
解决办法
8万
查看次数

何时在Angular2打字稿中创建构造函数?

以下是Angular 2文档中的一些示例构造函数:

export class AppComponent implements OnInit {
    title = 'Tour of heroes';
    heroes: Hero[];
    selectedHero: Hero;

    constructor(private heroService: HeroService) { }

    getHeroes() {
        this.HeroService.getHeroes().then(heroes => this.heroes = heroes);
    }
}
Run Code Online (Sandbox Code Playgroud)

和...

class Car {
    constructor(engine, tires, doors){
        this.engine = engine;
        this.tires = tires;
        this.doors = doors;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么以及何时创建一个constructor()角度2 /打字稿(我已经阅读了官方文档,他们为依赖注入和服务创建了一个构造函数).

typescript angular

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

Angular测试如何防止ngOnInit调用直接测试方法

上下文

我有一个组件.在其中,ngOnInit函数调用组件的另一个函数来检索用户List.我想制作两个系列的小说:

  • 首先测试ngOnInit是否正确触发并填充用户列表
  • 我想第二次测试我的刷新函数,它也调用getUserList()

第一个测试,使用ngOnInit触发器,当我调用fixture.detectChanges()时可以正常工作.

问题

我的问题是在测试刷新功能时:只要我调用fixture.detectChanges(),就会触发ngOnInit,然后我无法知道结果的来源以及我的refresh()函数是否会被正确测试.

在我对refresh()方法进行第二系列测试之前,有没有办法"删除"或"阻止" ngOnInit() 所以它没有被调用fixture.detectChanges()

我试着看,overrideComponent但它似乎不允许删除ngOnInit().

或者除了fixture.detectChanges在我的情况下使用之外,有没有办法检测更改?

这是组件,存根服务和我的spec文件的代码.

零件

import { Component, OnInit, ViewContainerRef } from '@angular/core';

import { UserManagementService } from '../../shared/services/global.api';
import { UserListItemComponent } from './user-list-item.component';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
  public userList = [];

  constructor(
    private _userManagementService: UserManagementService,    
  ) { }

  ngOnInit() {
    this.getUserList();
  }

  onRefreshUserList() {
    this.getUserList();
  }

  getUserList(notifyWhenComplete = false) { …
Run Code Online (Sandbox Code Playgroud)

jasmine typescript karma-jasmine angular

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

d3.js或rxjs错误?this.svg.selectAll(...).data(...).enter不是函数

这很奇怪.它也有点长,所以提前道歉. 更新 - 它最终成为2个问题,请参阅下面的答案.

这是我的错误: EXCEPTION: this.svg.selectAll(...).data(...).enter is not a function

我有一个angular-cli客户端和一个节点api服务器.我可以使用observable从服务中检索states.json文件(下面的代码).d3喜欢该文件并显示预期的美国地图.

当我将api服务器中的服务目标从文件更改为bluemix-cloudant服务器时,我在客户端收到上述错误.

当我使用ngOnInit在一个变体中使用console.log输出时,最初mapData打印为一个空数组,并抛出错误.这是错误的明显来源,因为没有数据,但Chrome调试器显示待处理的请求.请求完成后,数据将按预期在控制台中打印.

  • angular-cli版本1.0.0-beta.26
  • 角度版本^ 2.3.1
  • d3版本^ 4.4.4
  • rxjs版本^ 5.0.1

map.component.ts:

import { Component, ElementRef, Input } from '@angular/core';
import * as D3 from 'd3';
import '../rxjs-operators';

import { MapService } from '../map.service';

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

  errorMessage: string;
  height;
  host;
  htmlElement: HTMLElement;
  mapData;
  margin;
  projection;
  path;
  svg;
  width;

  constructor (private _element: ElementRef, private _mapService: MapService) {
    this.host = D3.select(this._element.nativeElement); …
Run Code Online (Sandbox Code Playgroud)

cloudant rxjs d3.js angular ibm-cloud

12
推荐指数
1
解决办法
1626
查看次数

使用构造函数在商店和ngOnInit上选择以便从商店调度

我的问题涉及从ngrx商店调度选择.

让我们看看官方示例应用程序中的以下代码:

export class CollectionPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.books$ = store.select(fromBooks.getBookCollection);
  }

  ngOnInit() {
    this.store.dispatch(new collection.Load());
  }
}
Run Code Online (Sandbox Code Playgroud)

我想了解选择调度ngOnInit选择的constructor动机是什么.

有人可以提供解释吗?

PS顺便说一下,上面是ngrx示例应用程序的示例代码,可以在这里找到:https://github.com/ngrx/platform/blob/master/example-app/app/books/containers/collection-page .TS

ngrx ngrx-store ngrx-store-4.0

12
推荐指数
2
解决办法
2158
查看次数

Angular2 router.navigate()第一次不工作

我定义了以下路线:

export const routes: Routes = [
    { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuardService] },
    { path: 'sites', component: SiteIndexComponent, resolve: { siteSummaries: SiteSummariesResolve }, canActivate: [AuthGuardService] },
    { path: 'qa-tasks', component: QaTaskIndexComponent, resolve: { investigations: InvestigationsResolve, reviews: ReviewsResolve }, canActivate: [AuthGuardService] },
    { path: 'error', component: ErrorComponent },
    { path: '**', redirectTo: '' }
];
Run Code Online (Sandbox Code Playgroud)

我的应用程序的用户根据他们的角色看到完全不同的页面,包括他们的"登陆"(主页)页面.我正在使用我的HomeComponent根据以下角色将用户路由到正确的登录页面:

export class HomeComponent implements OnInit {

    private roles: any;

    constructor(private router: Router,
        private authService: AuthService) { }

    ngOnInit() {
        var currentUser …
Run Code Online (Sandbox Code Playgroud)

angular2-routing angular

10
推荐指数
1
解决办法
6505
查看次数

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

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

谢谢.

typescript angular angular-lifecycle-hooks

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

设置布尔打字稿的默认值

我有一个对象:

export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday: boolean;
    isTuesday: boolean;
    isWednesday: boolean;
    isThursday: boolean;
    isFriday: boolean;
    fromDateToReturn: Date;
    toDateToReturn: Date;
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用它

  if (this.reccurrenceSelected === true) {
      this.reccurrence.isMonday = this.mondaySelected;
      this.reccurrence.isTuesday = this.tuesdaySelected;
      this.reccurrence.isWednesday = this.wednesdaySelected;
      this.reccurrence.isThursday = this.thursdaySelected;
      this.reccurrence.isFriday = this.fridaySelected;
}
Run Code Online (Sandbox Code Playgroud)

我想为它们设置一个默认值 - false 因为如果我不在 UI 中设置它们,它们将是未定义的,我不想要那样。

如何在打字稿中设置布尔值的默认值?

boolean typescript angular

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

Angular2将属性传递给类构造函数

如何将属性从父组件传递到其子组件的类构造函数Angular 2

计算出一半的神秘感,因为属性可以毫无问题地传递给视图.

/client/app.ts

import {Component, View, bootstrap} from 'angular2/angular2';
import {Example} from 'client/example';

@Component({
  selector: 'app'
})
@View({
  template: `<p>Hello</p>
    <example [test]="someAttr"
      [hyphenated-test]="someHyphenatedAttr"
      [alias-test]="someAlias"></example>
    `,
  directives: [Example]
})
class App {
  constructor() {
    this.someAttr = "attribute passsed to component";
    this.someHyphenatedAttr = "hyphenated attribute passed to component";
    this.someAlias = "attribute passed to component then aliased";
  }
}

bootstrap(App);
Run Code Online (Sandbox Code Playgroud)

/client/example.ts

import {Component, View, Attribute} from 'angular2/angular2';

@Component({
  selector: 'example',
  properties: ['test', 'hyphenatedTest', 'alias: aliasTest']
})
@View({
  template: `
    <p>Test: …
Run Code Online (Sandbox Code Playgroud)

typescript angular

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

为什么我应该在构造函数中创建Angular2反应形式而不是ngOnInit?

其他响应所示,Angular2应用程序的初始例程应该在ngOnInit()方法中启动,使构造函数专门用于依赖注入.

但是,在我正在关注的Reactive Forms教程中,表单的初始化在构造函数中:

export class HeroDetailComponent3 {
  heroForm: FormGroup; // <--- heroForm is of type FormGroup

  constructor(private fb: FormBuilder) { // <--- inject FormBuilder
    this.createForm();
  }

  createForm() {
    this.heroForm = this.fb.group({
      name: '', // <--- the FormControl called "name"
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

是真的有重大差异还是只是一个小问题?

constructor angular2-forms angular

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