如何访问Angular成分中JSON对象的字段[Angular 11]
这是我的角服务中调用简单rest API的方法:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Token } from './Token';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TokenServiceService {
constructor(private http: HttpClient) { }
public getToken(code:any):Observable<Token> {
const url = 'http://example.com/token?code='+ code +'&state=STATE123';
return this.http.get<Token>(url);
}
}
token:
export interface Token {
some_val:String;
some_val2:String;
some_val3:String;
}
这是调用上述方法的组件中的
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Token } from '../Token';
import { TokenServiceService } from '../token-service.service';
import { GlobalComponent } from '../global-component'
@Component({
selector: 'app-accesstoken',
templateUrl: './accesstoken.component.html',
styleUrls: ['./accesstoken.component.css']
})
export class AccesstokenComponent implements OnInit {
public token!:Token;
constructor(private route: ActivatedRoute, private tokenService: TokenServiceService) {}
ngOnInit(): void {
const code = this.route.snapshot.queryParamMap.get('code');
this.tokenService.getToken(code).subscribe(data => this.token = data)
console.log('obj : '+this.token)
console.log(this.token.some_val)
}
}
代码
obj :undefined
ERROR TypeError: Cannot read properties of undefined (reading 'some_val')
段成功地在UI上显示JSON对象(token):
<pre>{{token | json}}</pre>
但是,如何在我的组件类本身中访问token obj的字段而不显示在GUI上?我想将一些字段设置为浏览器cookie。
Here is the method from my Angular service calling a simple REST API:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Token } from './Token';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TokenServiceService {
constructor(private http: HttpClient) { }
public getToken(code:any):Observable<Token> {
const url = 'http://example.com/token?code='+ code +'&state=STATE123';
return this.http.get<Token>(url);
}
}
Token:
export interface Token {
some_val:String;
some_val2:String;
some_val3:String;
}
Here is the code snippet from the component that calls the above method:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Token } from '../Token';
import { TokenServiceService } from '../token-service.service';
import { GlobalComponent } from '../global-component'
@Component({
selector: 'app-accesstoken',
templateUrl: './accesstoken.component.html',
styleUrls: ['./accesstoken.component.css']
})
export class AccesstokenComponent implements OnInit {
public token!:Token;
constructor(private route: ActivatedRoute, private tokenService: TokenServiceService) {}
ngOnInit(): void {
const code = this.route.snapshot.queryParamMap.get('code');
this.tokenService.getToken(code).subscribe(data => this.token = data)
console.log('obj : '+this.token)
console.log(this.token.some_val)
}
}
Console output [here is the problem]:
obj :undefined
ERROR TypeError: Cannot read properties of undefined (reading 'some_val')
This tag in html successfully displays Json object (token) on UI:
<pre>{{token | json}}</pre>
But how can I access fields from token obj in my component class itself without displaying on GUI? I Want to set some fields to a browser cookies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是问题在于
.subscribe()
的异步性质和总体上可观察到。在中accessTokenComponent
您的console.log
行在 this.token = data = data必须等待可观察到的解决方案。调用subscribe
方法不会使您的代码等待可观察到的可观察到的执行,而是可以注册一旦可观察到的可调用,该回调将被调用。我敢打赌,如果将这些日志放入subscribe
回调中,则在分配后,您将可以看到this.token
的内容。编辑:
您还希望在模板中渲染此令牌值。为此,我建议您熟悉 async pipe 一个
可观察的&lt; gt;
,然后您必须在模板中使用| async
派遣它来渲染它)My guess is that the problem is with the asynchronous nature of
.subscribe()
and Observables in general. InAccesstokenComponent
yourconsole.log
lines are going to be called before thethis.token = data
assignment, which has to wait for the observable to get resolved. Calling thesubscribe
method doesn't make your code to wait for the execution of that observable, instead you can register the callback that's going to be invoked once the observable is ready. I bet if you put those logs inside thesubscribe
callback, after the assignment, you'd be able to see the contents ofthis.token
.EDIT:
You also want to render this token value in the template. For this purpose I'd recommend getting familiar with the async pipe (basically if you make your field an
Observable<something>
, then you've got to call it in the template with| async
to render it)