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

未完待续...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,601评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,367评论 1 305
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,249评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,539评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,967评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,929评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,098评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,825评论 0 207
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,609评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,796评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,282评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,603评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,277评论 3 242
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,159评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,959评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,079评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,874评论 2 277

推荐阅读更多精彩内容

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