【问题标题】:NG2339: Property does not exist on type 'Object'NG2339:“对象”类型上不存在属性
【发布时间】:2020-01-15 16:20:06
【问题描述】:

我尝试重复此代码:code

但不能,因为返回的错误如下:

src/app/page/page.component.html:1:28 - 错误 NG2339:“对象”类型上不存在属性“图像”。 1

src/app/page/page.component.ts:8:16

8 templateUrl: './page.component.html',

组件PageComponent的模板出现错误。

import { Component, OnInit } from '@angular/core';
import { ContentService } from '../shared/services/content.service';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {
  page: Object;

  constructor(private route: ActivatedRoute,
    private contentService: ContentService) { }

ngOnInit() {
  const pageData = this.route.snapshot.data['page'];
  this.page = this.contentService.pages[pageData];
}
}

我不知道如何解决它。请帮忙

【问题讨论】:

  • 您是否在 html 中调用 page.image
  • 问题出在您的 html 文件中,如错误所示,因此如果我们要帮助您,您也需要发布该文件。
  • 这还返回什么对象类型? this.contentService.pages[pageData]如果你有一个类型,那么页面应该是那个类型而不是Object
  • const pageData 的值是多少? ContentService pages 属性是否包含一个值为 const pageData 的对象作为它的键?

标签: angular


【解决方案1】:

你有一个 html 错误并且你没有显示 html ?

不建议将变量键入为 Object,请键入 any。

试试这个:

import { Component, OnInit } from '@angular/core';
import { ContentService } from '../shared/services/content.service';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {
  page: any;

  constructor(private route: ActivatedRoute,
    private contentService: ContentService) { }

  ngOnInit() {
    const pageData = this.route.snapshot.data['page'];
    this.page = this.contentService.pages[pageData];
  }
}

在你的 html 中显示你的变量,试试这个:

{{page?.image}}

如果它有效,欢迎您! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 2018-02-10
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 2020-09-27
    • 2021-04-02
    相关资源
    最近更新 更多