Angular 2 return data from RxJs subscribe

前端 未结 2 339
无人共我
无人共我 2020-12-24 08:24

I\'ve a service with an authenticate function -

authenticate(username: string, password: string) {
        let ret;
        let packet = JSON.stringify({
            


        
相关标签:
2条回答
  • 2020-12-24 09:01

    You need to return the observable corresponding your request directly:

    authenticate(username: string, password: string) {
      let ret;
      let packet = JSON.stringify({
        username: username,
        password: password
      });
    
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
    
      return this.http.post('http://localhost:5000/api/authenticate/', packet, {
        headers: headers
      })
      .map(res => res.json());
    }
    

    And the caller of the authenticate method must subscribe on it to receive the result:

    this.service.authenticate('username', 'password').subscribe(
      (result) => {
        console.log('Result received');
        console.log(result);
      }
    );
    
    0 讨论(0)
  • 2020-12-24 09:17

    I used Observables and Observers to build my solution. Since @Injectable creates a singleton class, I declared an Observable inside of it which I then exposed to my component. When I put any data into it, all subscribers get notified of the event. Warning: if you use this with zone.js 0.5, it won't work. Works with 0.6.

    import {Observable} from 'rxjs/Observable';
    import {Observer} from 'rxjs/Observer';
    import 'rxjs/add/operator/share';
    import 'rxjs/add/operator/map';
    import 'rxjs/Rx';
    
    
    @Injectable()
    export class AuthService {
        // expose to component
        notification$: Observable<Notification>;
        private observer: Observer<Notification>;
    
        ....
    
        constructor(private http: Http) {
            this.notification$ = new Observable(observer => this.observer = observer).share();
        }
    
        authenticate({username, password}) {
            let packet = JSON.stringify({
                username: username,
                password: password
            });
    
            let headers = new Headers();
            headers.append('Content-Type', 'application/json');
    
            this.http.post(`${this.baseUri}/authenticate/`, packet, {
                headers: headers
            })
            .map(res => res.json())
            .subscribe(
                data => {
                    if (data.success && data.token) {
                        this.saveJwt(data.token);
                    } else {
                        this.deleteJwt();
                    }
                    // put data into observavle 
                    this.observer.next({
                        message: data.message,
                        type: data.success
                    });
                },
                err => {
                    // put data into observavle  
                    this.observer.next({
                        message: 'Error connecting to server',
                        type: false
                    })
                },
                () => {}
            );
        }
    }
    
    
    export class AuthComponent implements OnInit {
        observable: Observable<Notification>;
    
        ...
    
        ngOnInit() {
            // subscribe to the observable
            this.observable = this.authService.notification$;
            this.observable.subscribe(
                data => {
                    ...
                }
            )
        }
    }
    
    0 讨论(0)
提交回复
热议问题