代码之家  ›  专栏  ›  技术社区  ›  nimrod

Google Chrome(Web组件)中未解析角度6变量

  •  3
  • nimrod  · 技术社区  · 7 年前

    使用Angular6,我创建了一个从另一个应用程序集成的Web组件。在没有集成的情况下运行时,所有浏览器都能正常工作。当Web组件集成到其他应用程序中时,它可以在IE、Safari、FF上工作,但不能在Chrome上工作。

    我设法找出了问题所在。第一个调用从我的后端获取一些配置数据。应该写进var this.conf 但当集成时,在Chrome中不会发生这种情况。

    我的组件:

    public conf: any;
    
    ngOnInit() {
      this.getData();
      console.log('Conf ngOnInit:', this.conf);
    }
    
    getData() {
      return this.partnerService.getData(this.name)
        .subscribe(
          (partner: any) => {
            console.log('partner: ', partner);
            this.conf = {
              id: partner['id'],
              name: partner['name']
            }
            console.log('conf:', this.conf);
         )
    }
    

    合作伙伴服务:

    @Injectable()
    export class PartnerService {
    
      constructor(public http: HttpClient) {
      }
    
      getData(name: string) {
        return this.http.get(environment.apiUrl + 'partners/conf/' + name)
          .map(resp => resp['partner']);
      }
    }
    

    我的观点:

    <pre>Conf: {{ conf | json }}</pre>
    

    控制台输出:

    Conf ngOnInit: undefined
    partner: {id: 1, name: "xxx", booking_name: "xxx", …}
    conf: {id: 1, name: "xxx"}
    

    在视图中未解析var。这可能是什么?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Drenai    7 年前

    注入 ChangeDetectorRef 在视图组件的构造函数中:

    constructor(private cd: ChangeDetectorRef) {
    }
    

    在subscribe函数中,尝试:

    this.conf = {};
    this.conf.id = partner['id'];
    this.conf.name = partner['name'];
    this.cd.detectChanges();
    

    这可能是计时/更改检测勾选的问题,只在Chrome中显示。至少它可以从等式中排除

        2
  •  0
  •   federico scamuzzi    7 年前

    我认为你的问题是异步流…当你把你的 console.log('Conf ngOnInit:', this.conf); 在nginit中,还没有填入 this.partnerService.getData(this.name)

    试试这个>

    public conf: any;
    
    ngOnInit() {
          this.getData().subscribe(()=>{
         console.log('Conf ngOnInit:', this.conf);
    });
    
    
    }
    
    getData() {
      return Observable.From(this.partnerService.getData(this.name)
        .subscribe(
          (partner: any) => {
            console.log('partner: ', partner);
    
            this.conf = {};
             this.conf.id = partner['id'];
              this.conf.name: partner['name'];
            console.log('conf:', this.conf);
         ))
    }
    
        3
  •  0
  •   Daniel Segura Pérez    7 年前

    编辑:新解决方案。尝试:

    <pre *ngIf="conf && conf.id && conf.name">Conf: {{ conf | json }}</pre>
    
    推荐文章