转换Observable< Object>到字符串 [英] Convert Observable<Object> to String

查看:102
本文介绍了转换Observable< Object>到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了

但是之后,我无法访问或转换它:

  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&lt; Object&gt;到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆