角度4-如何从另一个HTTP请求中的一个HTTP请求同步获取价值? [英] Angular 4 - How can get value synchronously from an http request in another http request?

查看:68
本文介绍了角度4-如何从另一个HTTP请求中的一个HTTP请求同步获取价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular 4用于我的客户端应用程序.

I'm using Angular 4 for my client application.

customer.service中的getCustomer()函数调用API来获取数据.此功能是可观察的.

The getCustomer() function in customer.service calls an API to get data. This function is Observable.

此功能需要访问令牌才能调用API.并且可以从auth.service中的getAccessToken()函数获取访问令牌.

This function needs an access token to be able to call the API. And the access token can be gotten from getAccessToken() function in auth.service.

但是getAccessToen()是异步的.我们如何从异步函数中获取价值?

But getAccessToen() is async. How can we get value from the async function?

请注意,getCustomer()必须是可观察的,以便我可以映射响应中的数据并绑定到customer.component的成员.

Note that getCustomer() must be Observable so that I can map data from response and bind to members of customer.component.

auth.service.ts

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
    private tokenEndpoint = "http://localhost:9000/connect/token";
    private clientId = "testclientid";
    private clientSecret = "testsecret";

    constructor(private http: Http) { }

    getAccessToken() : Observable<any> {
        let credential = "Basic " + btoa(`${this.clientId}:${this.clientSecret}`);
        let body = "grant_type=client_credentials&scope=testscope";
        let headers = new Headers();
        headers.set("Content-Type", "application/x-www-form-urlencoded");
        headers.set("Authorization", credential);   

        return this.http.post(this.tokenEndpoint, body, { headers: headers })
            .map(result => {
                let data = result.json();
                return data.access_token || "";
            });                     
    }
}

customer.service.ts

customer.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { Customer } from './customer';
import { Address } from './customer';
import { ResourceData } from './customer';
import { ResourceAttributes } from './customer';
import { CustomerResource } from './customer';
import { ResourceCollection } from './customer';
import { AuthService } from '../auth/auth.service';

@Injectable()
export class CustomerService {
    private customersUrl = "http://localhost:60001/api/v1/customers";

    constructor(private http: Http, private authService: AuthService) { }
    
    getCustomer(id: string): Observable<CustomerResource> {
		let accessToken = this.authService.getAccessToken().subcribe(
			// how to get accessToken from authService because subcribe is async?
		); 
		
		let headers = addAccessTokenToHeader(accessToken);
	
        let url = `${this.customersUrl}/${id}`;
        return this.http.get(url, { headers: headers })
            .map(result => {                
                return result.json() as CustomerResource;
            })
            .catch((error) => {
                console.log(error);
                return Observable.throw(error);
            });
    }    

	private addAccessTokenToHeader(accessToken: string): Headers {
        let headers = new Headers();
        headers.set("Authorization", `Bearer ${accessToken}`);

        return headers;
    }
}

customer-detail.component.ts

customer-detail.component.ts

showCustomer(id: string) {
    this.modalTitle = "Update PL customer";
    this.buttonSaveTitle = "Update";
    this.customerService.getCustomer(id)
        .subscribe(customer => {
            this.mapFromResource(customer.data);
            this.customerModal.show();
        });
}

private mapFromResource(data: ResourceData) {
    this.customerId = data.id;
    this.reference = data.attributes.reference;
    this.lastName = data.attributes.lastName;
    this.middleName = data.attributes.middleName;
    this.firstName = data.attributes.firstName;
}

// this.customerId, this.reference are the members of customer.component. They are binding on UI.

推荐答案

我正在使用flatMap,现在可以使用了.非常感谢您的建议@ AJT_82

I'm using flatMap and it works now. Thank you very much for your suggestions @AJT_82

这篇关于角度4-如何从另一个HTTP请求中的一个HTTP请求同步获取价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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