移动HTTP functionaity到自己的服务与Angular2和打字稿 [英] Move http functionaity into its own Service with Angular2 and TypeScript

查看:140
本文介绍了移动HTTP functionaity到自己的服务与Angular2和打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前想后角1 *愉快地工作在过去4年自学Angular2和打字稿!无论如何,我有一个创建一个从我在另一个类创建的类型派生的属性顶级组件。随着我的组件时, ngOnInit()叫我做一个 HTTP 调用一个骗子REST服务,我写了一回结束。现在,使用AngularJS编写应用程序的时候我都会把我的 $ HTTP 任务到服务,并将其注入到我的控制器......我愿做同样的我的组件。这里是我没有激活服务code成分...注意到的评论

I'm currently trying to teach myself Angular2 and TypeScript after happily working with Angular 1.* for the last 4 years! Anyway, I have a top level component that creates a property that is derived from a type I have created in another class. With my component when ngOnInit() is called I make a http call to a phoney REST service I wrote as a back end. Now when writing apps using AngularJS I would put my $http tasks into a service and inject them into my controllers... I would like to do the same with my component. Here's my component without the service code activated... notice the comments

import {Component, OnInit} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Home} from './components/home/home';
import {UserStatus} from './types/types.ts'; // this is why my UserStatus Type is kept
import {UserData} from './services/user-data/UserData.ts'; // here is where I wish to write my sevice to perform the http tasks...
import {Http, Headers} from 'angular2/http';

@Component({
    selector: 'app', // <app></app>
    providers: [...FORM_PROVIDERS],
    directives: [...ROUTER_DIRECTIVES],
    pipes: [],
    styles: [require('./app.scss')],
    template: require('./app.html')
})

export class App {

    userStatus: UserStatus;

    constructor(public http: Http) {
        this.userStatus = new UserStatus();
    }

    ngOnInit() {

        // I really want to put this code into a seperate class and provide it as a service...
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.get('/restservice/userstatus', {headers: headers})
            .map((data: any) => data.json())
            .subscribe(
            (data: any) => {
                this.userStatus = data;
            },
            err => console.log(err), // error
            () => console.log('getUserStatus Complete') // complete

        );

        /* I'd like to factor the above into a service kept in a diffent file like so*/
        /*

         UserData.getUserStatus().then((resp) => {
            this.userStatus = resp;
         })
         */

    }
}

现在这里是我喜欢的类型......我的 userStatus 属性...

Now here is my type... for my userStatus property...

export class UserStatus {

    constructor (
        public firstName?: string,
        public fullPersId?: number,
        public goldUser?: boolean,
        public hasProfileImage?: boolean,
        public hideMoblieNavigationAndFooter?: boolean,
        public persId?: string,
        public profileName?: string,
        public profilePicture?: string,
        public showAds?: boolean,
        public siteId?:  number,
        public url?: string,
        public verified?: boolean,
        public appOS?: any,
        public formerName?: any
    ) {

        this.firstName = firstName || '';
        this.fullPersId = fullPersId || 0;
        this.goldUser = goldUser || false;
        this.hasProfileImage = hasProfileImage || false;
        this.hideMoblieNavigationAndFooter = hideMoblieNavigationAndFooter || false;
        this.persId = persId || '';
        this.profileName = profileName || '';
        this.profilePicture = profilePicture || '';
        this.showAds = showAds || false;
        this.siteId =  siteId || 0;
        this.url = url || '';
        this.verified = verified || false;
        this.appOS = appOS || null;
        this.formerName = formerName || null;

    }
}

现在我希望把我的组件的断点续传功能成serperate服务......我开始写以下code(大家不要笑,我真的是新来Angular2)

Now I wish to put the http functionality of my Component into a serperate service... I started to write the following code (PLEASE DON'T LAUGH, I really am new to Angular2)

import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import {UserStatus} from '../../types/types.ts';

@Injectable()
export class UserData {

    constructor(public http:Http) {
    }

    getUserStatus(): any {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.get('/restservice/userstatus', {headers: headers})
            .map((data: any) => data.json())
            .subscribe(
            (data: any) => {
                return data;
            },
            err => console.log(err), // error
            () => console.log('getUserStatus Complete') // complete
        );
    }
}

现在我希望我可以打电话给服务 getUserStatus()方法来执行的HTTP数据获取,并呼吁它在我的应用组件类似的信息(我使用AngularJS 1.x的承诺的例子,但我知道我应该真正使用观测...我只是不知道如何!)

Now I was hoping I could call the service getUserStatus() method to perform the HTTP data fetch and call it in my App Component something like (I am using AngularJS 1.x promise example, but I know I should really use observables... I just don't know how!)

ngOnInit() {

     UserData.getUserStatus().then((resp) => {
        this.userStatus = resp;
     });

    }

这显然是垃圾,我不知道我在做什么(例如/为Angular2教程似乎并没有被这个伟大的或实践到目前为止)。是否有人可以展示我如何连接服务的话,正确地调用它在我的组件?

This is obviously rubbish and I don't know what I am doing (examples/tutorials for Angular2 don't seem to be that great or practical so far). Can someone please show my how to wire the service then call it correctly in my Component?

推荐答案

我喜欢这个问题,因为我也去了同一条路,不得不重构我的code。
所以,最好的做法,现在有RxJs观测是不是从HTTP请求返回的JSON在.subscribe()方法。只是映射它并返回它。
你在做什么有一个从所有额外的信息有剥离它。

I like this question because I went down the same road too and had to refactor my code. So best practice right now with RxJs observables is not to return the json in your .subscribe() method from the http request. Just map it and return it. What you are doing there is stripping it from all of the extra info it has.

您应该返回观察到这是整个执行的get()。

You are supposed to return the observable which is the whole implementation of the get().

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

private handleError(error: Response) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

然后在你的组件一侧你可以简单地订阅可观察

Then on your component side you can simply subscribe to the observable

export class App {
    public userStatus:any;
    // Have to inject the UserData Service it into our component here.
    constructor(public http: Http, private _userData: UserData ) {
    }

    ngOnInit() {
         this._userData.getUserStatus()
         .subscribe(
            (status) => {
              this.userStatus = status;
            },
            (err) => {
              console.log(err);
            },
            ()=>{console.log("User status complete")}
         );

        }
}

这篇关于移动HTTP functionaity到自己的服务与Angular2和打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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