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);
  }

}

父级模板内使用:

<ar-search [arClick]="printMsg"></ar-search>

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}

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

(<any>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、上个星期碰到的印象最深的一个问题。

问题描述(直接上图):



首先因为找了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 : '<div class="foot" id="footer"><div #dynamiccompile></div></div>',
  providers : [FooterService]
})

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

  }

  ngAfterViewInit () {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.footerService.getHtmlCode().subscribe(
      res =>
        (
          (this.compileToComponent("<div (click)='test()'>click</div>")).then((factory: ComponentFactory<any>) => {
            this.cmpRef = this.target.createComponent(factory)
          })
        ),
      error => console.log(<any>error)
    )
  }
  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }

  private compileToComponent(template1: string): Promise<ComponentFactory<any>> {

    @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)
    )
  }
}

未完待续...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 每次在外面闹哄哄地或玩或聚或出差几天后就特别盼望回家。回到那个熟悉的屋子,每件物品都是自己心怡的,所有的饰品都由自...
    杨紫凌阅读 607评论 0 0
  • 最近读了篇英文文章,很有共鸣,分享给大家。 满足感来自于哪里? 我们都有渴望灵魂伴侣的渴望,渴望着梦想有一天,遇到...
    霞光十色阅读 1,676评论 6 7
  • 一个漂洋过海的拥抱 携满风声与泪光 ...
    你看见我的龙猫了吗阅读 349评论 0 0
  • 最近看到网上有一篇文章《狗日的中年》,看了以后感叹造化弄人…… “想不到一奔子就挖到中年,才发现中年碎了一地的烟火...
    841fd886a8c5阅读 19,288评论 2 0
  • 男孩子不用从小做家务,等成家了,有媳妇做就行了。 男孩子不用太会做家务,免得结婚后给媳妇当牛做马。 男孩子做什么家...
    西园草阅读 5,349评论 2 14