相关疑难解决方法(0)

使用TypeScript从Angular2中的http数据链接RxJS Observable

在过去的4年里,我在与AngularJS 1.*一起工作之后,我正在尝试自学Angular2和TypeScript!我不得不承认我讨厌它,但我确信我的尤里卡时刻即将到来......无论如何,我已经在我的虚拟应用程序中编写了一个服务,它将从我写的服务JSON的虚拟后端获取http数据.

import {Injectable} from 'angular2/core';
import {Http, Headers, Response} from 'angular2/http';
import {Observable} from 'rxjs';

@Injectable()
export class UserData {

    constructor(public http: Http) {
    }

    getUserStatus(): any {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('/restservice/userstatus', {headers: headers})
            .map((data: any) => data.json())
            .catch(this.handleError);
    }

    getUserInfo(): any {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get('/restservice/profile/info', {headers: headers})
            .map((data: any) => data.json())
            .catch(this.handleError);
    }

    getUserPhotos(myId): any {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get(`restservice/profile/pictures/overview/${ myId }`, …
Run Code Online (Sandbox Code Playgroud)

observable rxjs typescript angular

89
推荐指数
1
解决办法
5万
查看次数

Ionic 2 - 从存储值获取令牌并在HTTP请求之前设置Header

我在登录后使用该ionic/storage包来存储api_tokenfor用户,因此我可以使用唯一令牌与API进行交互.

我面临的问题是我需要获取值,通过storage.get该值返回一个promise并导致我想要设置的标题没有及时设置.

我需要返回一个RequestOptions实例,但无法弄清楚如何添加我从promise中检索到的头.添加与localStorage同步的头文件在测试时工作正常,因此问题必须是异步执行.

createAuthorizationHeader(headers: Headers) {
    // this does add the header in time
    localStorage.setItem('api_token', 'some token');
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('api_token'));

    // this does not add the header in time
    return this.storage.get('api_token').then((value) => {
        headers.append('Authorization', 'Bearer ' + value);
    });
}

getHeaders(path): RequestOptions {
    let headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    if(!this.isGuestRoute(path)) {
        this.createAuthorizationHeader(headers);
    }

    return new RequestOptions({ headers: headers });
}

get(path: string) {
    return this._http.get(this.actionUrl + path, this.getHeaders(path)) …
Run Code Online (Sandbox Code Playgroud)

http web-sql ionic2 angular

3
推荐指数
1
解决办法
3849
查看次数

标签 统计

angular ×2

http ×1

ionic2 ×1

observable ×1

rxjs ×1

typescript ×1

web-sql ×1