错误TypeError:无法读取未定义的属性“ IsOnline”
我想使用角度6 Http get()
请求从django服务器获取数据,但遇到此错误。我当前的代码如下:
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)
}
}
get.service.ts:
@Injectable()
export class GetService {
constructor (private http: HttpClient) {}
private _url: string = "/test/";
getUser() {
return this.http.get(this._url)
}
}
我的服务器的响应如下:
{'isOnline': True}
预先感谢您对问题的解释。
答案 0 :(得分:1)
由于尝试在this.dummy
方法中检索其isOnline
属性而未定义getProfile
时,发生类型错误错误。而且,dummy
在访问其isOnline
属性之前从未分配值,getProfile
不返回值,并且无法从您的getProfile
返回配置文件方法,因为需要通过对getUser
的异步调用来检索配置文件。
这可能与您要执行的操作一致:
get.service.ts
export interface IProfile {
isOnline: boolean
}
@Injectable()
export class GetService {
private _url: string = "/test/";
constructor (private http: HttpClient) {}
getUser(): Observable<IProfile> {
return this.http.get(this._url) // returns an Observable
}
}
app.component.ts
import { IProfile, GetService } from "../services/get.service.ts"
@Component({
selector: 'app-root',
template: `
<div>
<button (click="loadUser()">Load profile</button>
<div *ngIf="profile">{{ profile | json }}</div>
<div *ngIf="isOnlime">IsOnline: {{ isOnline }}</div>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public profile: IProfile;
isOnline: boolean;
constructor(private _http: GetService) {}
loadUser(): void {
this._http.getUser().subscribe(profile => {
this.profile = profile
this.isOnline = profile.isOnline
})
}
}
这里loadUser
方法订阅getUser
,然后在observable发出一个异步发生的值时设置成员变量。
或者,您可以使用Angular的async
过滤器直接处理可观察对象:
import { IProfile, GetService } from "../services/get.service.ts"
@Component({
selector: 'app-root',
template: `
<div>
<button (click="loadUser()">Load profile</button>
<div>{{ profile | async | json }}</div>
<div>IsOnline: {{ (profile | async).isOnline }}</div>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public profile: Observable<IProfile>;
constructor(private _http: GetService) { }
loadUser(): void {
this.profile = this._http.getUser()
}
}
之所以可行,是因为Angular支持直接处理Promise和Observable。在上面,async
过滤器指示angular假定变量是可观察的(或一个promise),因此它将在内部订阅和取消订阅可观察的profile
。
祝你好运!