Convert Observable<Object> to String

余生颓废 提交于 2021-01-24 07:13:10

问题


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 } );

回答1:


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;
});



回答2:


Just use desired property and it is good practice to handle errors. You can see what properties are available by using console.log() - it will show your properties:

console.log(this.visitorService.getIpAddress()
    .subscribe(ip => {
        console.log(`your ip`, ip);
        this.ipAdress = ip['yourProperty'];
        },
    err => {
        console.log(err);
    });

UPDATE:

Your code looks ok for me. However, it can be improved by using pipe method just one time. pipe method is used to chain methods:

login(username: string, password: string): Observable<User> {
    // der globale interceptor (jwt) hängt halt auch 
    // hier das authorization header feld hinzu; macht nichts

    return this.http.post<UserRaw>(
      `${environment.apiUrl}/login`, { username, password } )
      .pipe(map(userRaw => UserFactory.fromRaw(userRaw)),
            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;
      }));

You can read more in Angular 2 Style Guide



来源:https://stackoverflow.com/questions/61340819/convert-observableobject-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!