转换Observable< Object>到字符串 [英] Convert Observable<Object> to String
问题描述
我找到了
但是之后,我无法访问或转换它:
this.visitorService.getIpAddress().subscribe(ip =&>; {this.ipAdress = ip.ip});
如果要将IP地址输出到控制台,则只能在值到达"后执行此操作:
this.visitorService.getIpAddress().subscribe(ip => {console.log(ip);this.ipAdress = ip;});
I've found this example of a service to get the IP-Address.
This service returns an Observable<Object>
, which I would like to assign/save to a String-Variable.
getIpAddress() {
return this.http
.get('https://api.ipify.org/?format=json')
.pipe(
catchError(this.handleError)
);
}
I'm still not well "trained" with Observables. I've injected this Service to my own Service (an Authentication Service) where I'm trying to access the actual value, which would be a string.
I know I'll have to subscribe and pipe/map in order to use it, but that's where I'm lost...
console.log(this.visitorService.getIpAddress().subscribe(ip => this.ipAdress = ip ?? ));
Lastly, I want to use the IP-Address (string) inside my login-method (where the console.log will be replaced and the API received this third body param):
login(username: string, password: string): Observable<User> {
// der globale interceptor (jwt) hängt halt auch hier das authorization header feld hinzu; macht nichts
console.log(this.visitorService.getIpAddress().subscribe(ip => this.ipAdress = ip ?? ));
return this.http.post<UserRaw>(
`${environment.apiUrl}/login`, { username, password } )
.pipe(map(userRaw => UserFactory.fromRaw(userRaw)))
.pipe(map(user => {
// local storage = client persistence (user bleibt eingeloggt)
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
// console.log(user.username);
return user;
}));
UPDATE
this.visitorService.getIpAddress().subscribe(ip => { console.log(ip); } );
returns
but afterwards, I can't access or convert it :
this.visitorService.getIpAddress().subscribe(ip => { this.ipAdress = ip.ip } );
If you want to output IP address to console, you can only do it once the value "arrives":
this.visitorService.getIpAddress().subscribe(ip => {
console.log(ip);
this.ipAdress = ip;
});
这篇关于转换Observable< Object>到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!