如果我希望每次加载组件时都会发生函数x,无论是第一次加载,我都会导航到另一个站点并导航回来,或者是组件第五次加载.
我应该把函数x放入什么?组件构造函数还是OnInit?
以下是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 /打字稿(我已经阅读了官方文档,他们为依赖注入和服务创建了一个构造函数).
我有一个组件.在其中,ngOnInit函数调用组件的另一个函数来检索用户List.我想制作两个系列的小说:
第一个测试,使用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) 这很奇怪.它也有点长,所以提前道歉. 更新 - 它最终成为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调试器显示待处理的请求.请求完成后,数据将按预期在控制台中打印.
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) 我的问题涉及从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
我定义了以下路线:
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) ngOnInit(),ngAfterViewInit(),ngafterContentInit(),ngAfterViewChecked()和构造函数()之间有什么区别?我们如何在Angular 2中实现它们?他们的目的和用途是什么?实施它们的所有方面都有用吗?
谢谢.
我有一个对象:
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 中设置它们,它们将是未定义的,我不想要那样。
如何在打字稿中设置布尔值的默认值?
如何将属性从父组件传递到其子组件的类构造函数Angular 2?
计算出一半的神秘感,因为属性可以毫无问题地传递给视图.
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)
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) 如其他响应所示,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)
是真的有重大差异还是只是一个小问题?
angular ×9
typescript ×5
constructor ×2
boolean ×1
cloudant ×1
d3.js ×1
ibm-cloud ×1
jasmine ×1
ngoninit ×1
ngrx ×1
ngrx-store ×1
rxjs ×1