Angular2项目日常开发中所遇问题及解决方案记录(二)

1、angular2 object undefined

问题描述:通过http>get()方法获取到的对象accountDetails = {userName : 'alice'}。

之后在页面里面通过取值表达式 {{accountDetails.userName}}进行展示。

结果报错: angular2 object undefined

解决方案:可以试试使用 ?. ,比如:{{accountDetails?.userName}}

2、父级Component向子级Component通过@Input()传入Function过程。

子级Component:

export class ChildComponent {
  @Input() arClick : Function;

  @HostListener('document:keydown',['$event'])
  onKeyDown (e : KeyboardEvent) {
    e.stopPropagation();
    if (e && e.keyCode == 13) {
      this.arClick('B');
    }
  }
}

父级Component:

export class FatherComponent {
  constructor () {

  }
  printMsg = (someText) => {
    console.log(someText);
  }

}

父级模板内使用:


3、关于Object.assign()方法的使用。

发现在代码中直接使用Object.assign()方法不行。之前网上有看到别人使用object-assign这个库:

var objectAssign = require('object-assign');

objectAssign({foo: 0}, {bar: 1});
//=> {foo: 0, bar: 1}

// multiple sources
objectAssign({foo: 0}, {bar: 1}, {baz: 2});
//=> {foo: 0, bar: 1, baz: 2}

// overwrites equal keys
objectAssign({foo: 0}, {foo: 1}, {foo: 2});
//=> {foo: 2}

// ignores null and undefined sources
objectAssign({foo: 0}, null, {bar: 1}, undefined);
//=> {foo: 0, bar: 1}

其实可以更简单的,试试这样:

(Object).assign({foo: 0}, {bar: 1})

只需加个any就ok了。

4、Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
在Component中连续多次修改一个属性值,F12页面有报这个错,找到几个解释。

Angular utilizes zones to know when an event is fully processed by patching some async APIs like (addEventHandler, setTimeout, ...) and then runs change detection after each event.

In dev mode Angular does an additional change detection run, just after the first one. Because there was no event in between, no change should have happened.

If the model still changed, Angular considers this to be a possible bug.

That's exactly it. In development mode the change detection runs a second time and compares the current value with the first run.

If the value differs, then it "thinks" that the change was caused by itself. That's why it throws. However this doesn't happen in production mode with enableProdMode().

解决方案:

import { Component, enableProdMode } from  '@angular/core';
enableProdMode();

5、上个星期碰到的印象最深的一个问题。

问题描述(直接上图):


Angular2项目日常开发中所遇问题及解决方案记录(二)_第1张图片

首先因为找了API发现本来这个DynamicComponentLoader是可以的,结果发现新版本已经被摒弃了。

所以就在stackoverflow上发帖,结果又被管理人员给我标记了,说是有类似的答案,纷纷去查看了下,发现并没有什么卵(luan)用。

所谓靠人还不如靠自己,接下来就是自己慢慢的摸索之路,所幸老天也不愿我在国庆放假前留下这么个遗憾。

最终的解决方案:把要编译(重新编译)的静态html封装成为一个Component,重新插入到页面里面去。(细的就不多说了...)

import {NgModule,
  Component, enableProdMode, ViewChild, ViewContainerRef, ComponentRef, Compiler,
  ComponentFactory
} from  '@angular/core';
import {FooterService} from "./footer.service";
import {BrowserModule} from "@angular/platform-browser";
import {RouterModule}  from "@angular/router";
import {Promise} from  'rxjs'
enableProdMode();
@Component({
  selector : 'footer',
  template : '',
  providers : [FooterService]
})

export class FooterComponent{
  @ViewChild('dynamiccompile',{read : ViewContainerRef}) target : ViewContainerRef;
  private cmpRef :  ComponentRef;
  constructor (
   private footerService : FooterService,
   private compiler : Compiler) {

  }

  ngAfterViewInit () {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.footerService.getHtmlCode().subscribe(
      res =>
        (
          (this.compileToComponent("
click
")).then((factory: ComponentFactory) => { this.cmpRef = this.target.createComponent(factory) }) ), error => console.log(error) ) } ngOnDestroy() { if (this.cmpRef) { this.cmpRef.destroy(); } } private compileToComponent(template1: string): Promise> { @Component({ template: template1, }) class DynamicComponent { test () : void { console.log('111'); } } @NgModule({ imports: [BrowserModule,RouterModule], declarations: [DynamicComponent] }) class DynamicModule { } return this.compiler.compileModuleAndAllComponentsAsync(DynamicModule).then( factory => factory.componentFactories.find(x => x.componentType === DynamicComponent) ) } }

未完待续...

你可能感兴趣的:(Angular2项目日常开发中所遇问题及解决方案记录(二))