javascript 无法读取未定义的 angular 7 的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53486476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cannot read property of undefined angular 7
提问by hesham shawky
I am getting many errors at the dev tools console when adding a service into my component but the code still working but I want to get rid of from these errors
将服务添加到我的组件中时,我在开发工具控制台上遇到许多错误,但代码仍在工作,但我想摆脱这些错误
This's the service:
这是服务:
getPagesData(pageSlug: string): Observable<any[]> {
return this._http.get<any[]>(`${environment.apiUrl}wp/v2/pages/?slug=${pageSlug}`);
}
This is the component:
这是组件:
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
@Component({
selector: 'app-membership',
templateUrl: './membership.page.html',
styleUrls: ['./membership.page.scss'],
})
export class MembershipPage implements OnInit {
public pageContent: any = {};
public content: string;
constructor(
private _data: DataService
) { }
ngOnInit() {
this._data.getPagesData('memberships')
.subscribe(
page => this.pageContent = page[0]
)
}
getContent(): string {
return this.pageContent.content.rendered.replace(/\[(.+?)\]/g, "");
}
}
What cause the errors is the getContent()method! it says that is the .renderedis an undefined property but it doses defined on the API!
导致错误的原因是getContent()方法!它说.rendered是一个未定义的属性,但它在 API 上定义了!
I have searched on that problem and most of the solutions I found it's about using the symbol ?at HTML template but I can't use that in the component itself.
我已经搜索过这个问题,我发现的大多数解决方案都是关于使用符号的?在 HTML 模板中,但我不能在组件本身中使用它。
回答by Pardeep Jain
Yes, you cannot use ?Elvis (Safe navigation) operator in the component itself because it is designed for view part only.
是的,您不能?在组件本身中使用Elvis(安全导航)运算符,因为它仅用于视图部分。
But you can add some check in the component too to avoid such errors like -
但是您也可以在组件中添加一些检查以避免此类错误,例如 -
getContent(): string {
const dataToReturn = this.pageContent && this.pageContent.content && this.pageContent.content.rendered.replace(/\[(.+?)\]/g, "");
return dataToReturn
}
.rendered is an undefined property
.rendered 是一个未定义的属性
Also, This error may produce you have defined pageContent = {}so on {}neither contentnor renderedexist , may be that is also the reason to exist such errors.
此外,此错误可能会导致您定义了pageContent = {}如此{}既不存在content也不rendered存在,可能这也是存在此类错误的原因。
Angular recommend to strongly typecast your data before use.
Angular 建议在使用前对数据进行强类型转换。
回答by Alexander Staroselsky
If you are calling getContent()in the HTML/template, you can most likely avoid this error by either:
如果您getContent()在 HTML/模板中调用,您很可能可以通过以下任一方式避免此错误:
Making pageContentinitially nulland using *ngIfto only display the content once it has asynchronously resolved:
pageContent最初制作null并使用*ngIf仅在异步解析后显示内容:
Component:
零件:
public pageContent: any = null;
Template:
模板:
<div *ngIf="pageContent">{{getContent()}}</div>
Or you could instead RxJS operators such as map()and the asyncpipe:
或者你可以代替 RxJS 操作符,例如map()和async管道:
Component:
零件:
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-membership',
templateUrl: './membership.page.html',
styleUrls: ['./membership.page.scss'],
})
export class MembershipPage implements OnInit {
public pageContent: Observable<string>;
public content: string;
constructor(private _data: DataService) { }
ngOnInit() {
this.pageContent = this._data.getPagesData('memberships')
.pipe(
map(page => page[0].content.rendered.replace(/\[(.+?)\]/g, ""))
);
}
}
Template:
模板:
<div>{{pageContent | async}}</div>
That being said, you should probably have additional checks to ensure each sub-property is available prior to accessing it, but usually this type of error is because you are attempting to access the contents before they have resolved.
话虽如此,您可能应该进行额外的检查以确保每个子属性在访问之前都可用,但通常这种类型的错误是因为您试图在内容解决之前访问它。
Hopefully that helps!
希望这有帮助!

