Angular 按键读取值的问题

Angular 按键读取值的问题,angular,angular6,Angular,Angular6,错误类型错误:无法读取未定义的属性“IsOnline” 我想使用angular 6httpget()request从django服务器获取数据,但遇到此错误。我当前的代码如下所示: {'isOnline': True} app.component.ts @Component({ selector: 'app-root', template: ' <div>\n' + ' <button (click="loadUser()">Load profi

错误类型错误:无法读取未定义的属性“IsOnline”

我想使用angular 6
httpget()
request从django服务器获取数据,但遇到此错误。我当前的代码如下所示:

{'isOnline': True}
app.component.ts

@Component({
    selector: 'app-root',
    template: ' <div>\n' +
    ' <button (click="loadUser()">Load profile</button>\n' +
    ' {{ getter | json }}\n' +
    ' </div>' +
    '',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app';
    public dummy = this.getProfile();
    IsOnline: boolean;
    getter = {};

    constructor(private _http: GetService) { }

    getProfile() {
        this._http.getUser().subscribe(data => this.getter = data);
        const descData = this.dummy['IsOnline'];
        console.log(descData)
    }
}
我的服务器的响应如下所示:

{'isOnline': True}

提前感谢您对该问题的解释。

发生类型错误是因为
当您试图在
getProfile
方法中检索其
isOnline
属性时,此.dummy
未定义。此外,
dummy
在访问它的
isOnline
属性之前从来不会被赋值,
getProfile
不会返回值,并且无法从
getProfile
方法返回配置文件,因为需要通过对
getUser
的异步调用来检索配置文件

这可能与您正在尝试的操作一致:

get.service.ts

导出接口IProfile{
等值线:布尔值
}
@可注射()
导出类GetService{
私有url:string=“/test/”;
构造函数(私有http:HttpClient){}
getUser():可观察的{
返回this.http.get(this.\uURL)//返回一个可观察的
}
}
应用程序组件.ts

从“./services/get.service.ts”导入{IProfile,GetService}
@组成部分({
选择器:'应用程序根',
模板:`
负荷剖面
{{profile | json}}
IsOnline:{{IsOnline}}
`,
样式URL:['./app.component.css']
})
导出类AppComponent{
标题=‘应用程序’;
公众简介:IProfile;
等值线:布尔;
构造函数(私有_http:GetService){}
loadUser():void{
这是http.getUser().subscribe(profile=>{
this.profile=profile
this.isOnline=profile.isOnline
})
}
}
这里的
loadUser
方法订阅
getUser
,然后在可观察对象发出值时设置成员变量,该值是异步发生的

或者,您可以使用Angular的
async
过滤器直接处理可观察到的:

从“./services/get.service.ts”导入{IProfile,GetService}
@组成部分({
选择器:'应用程序根',
模板:`
负荷剖面
{{profile | async | json}
IsOnline:{(profile | async).IsOnline}
`,
样式URL:['./app.component.css']
})
导出类AppComponent{
标题=‘应用程序’;
公众形象:可见;
构造函数(私有_http:GetService){}
loadUser():void{
this.profile=this.\u http.getUser()
}
}
这是因为Angular支持直接处理承诺和可观测数据。在上面的例子中,
async
过滤器指示angular假设变量是可观察的(或承诺),因此它将在内部订阅和取消订阅可观察的
配置文件


祝你好运

isOnline
isOnline
不同。这可能是问题的一部分吗?
getProfile
不返回任何内容,因此
public dummy=this.getProfile()
将把
this.dummy
设置为未定义(另外,正如您所知,您可以对模板字符串使用反勾号,而不是连接多个单行字符串)@user184994谢谢,直到现在才在我的mac电脑键盘上找到它们:)我想在pc 106key版本中,据我所知,它们是不可访问的
IProfile
是您创建界面的自定义名称吗?如果我希望JSON dict中有任何其他字段,我可以简单地通过名称和其中的预期类型来定义它们?@Chickenfresh,没错。我在
get.service.ts
中定义了
IProfile
,并从那里导出了它。严格来说,这不是必需的,但是这样做通常是很好的做法,并且根据其使用方式帮助进行类型检查和代码完成。仅供参考,我在第一个版本的
app.component.ts
{{profile | json}
中对tempate进行了更正性编辑。祝你一切顺利!谢谢真的很感激