简体   繁体   English

RxJs Observables和http angular2服务

[英]RxJs Observables and http angular2 service

I know there's a lot of tutorials over there about how to use RxJs/Observables. 我知道那里有很多关于如何使用RxJs / Observables的教程。

I need some very straightforward example in order to see how to use Observables with http angular2 service using map , subscribe and catch methods. 我需要,以了解如何使用观测量了一些非常简单的例子http使用angular2服务mapsubscribecatch方法。

Up to now, I've able to generate a service in order to get communication with a REST endpoint: 到目前为止,我已经能够生成服务以便与REST端点进行通信:

@Injectable()
export class UsersApi {
    protected basePath = 'http://localhost:8082/commty/cmng';

    constructor(protected http: Http) {

    }

    public create(user: string, passwd: string, extraHttpRequestParams?: any): Observable<{}> {
        return this.createWithHttpInfo(user, passwd, extraHttpRequestParams)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json();
                }
            });
    }

    public createWithHttpInfo(user: string, passwd: string, extraHttpRequestParams?: any): Observable<Response> {
        const path = this.basePath + `/users`;

        let queryParameters = new URLSearchParams();
        let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
        // verify required parameter 'user' is not null or undefined
        if (user === null || user === undefined) {
            throw new Error('Required parameter user was null or undefined when calling create.');
        }
        // verify required parameter 'passwd' is not null or undefined
        if (passwd === null || passwd === undefined) {
            throw new Error('Required parameter passwd was null or undefined when calling create.');
        }


        // to determine the Content-Type header
        let consumes: string[] = [
        ];

        // to determine the Accept header
        let produces: string[] = [
            'application/json'
        ];





        let requestOptions: RequestOptionsArgs = new RequestOptions({
            method: RequestMethod.Put,
            headers: headers,
            search: queryParameters
        });

        // https://github.com/swagger-api/swagger-codegen/issues/4037
        if (extraHttpRequestParams) {
            requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
        }

        return this.http.request(path, requestOptions);
    }

I've used map method but I don't quite understand what it stands for. 我使用过map方法,但我不太明白它代表什么。

How would I need to use UserApi.create(user, password) method? 我将如何使用UserApi.create(user, password)方法?

EDIT 编辑

Since http.get(...) method isn't going to be performed without a subscription , I figure out I need any stuff like: 由于http.get(...)方法不会在没有订阅的情况执行,因此我发现我需要以下任何东西:

userApi.create('user', 'password').subscribe(...)

Could somebody fill up subscribe method? 有人可以填写subscribe方法吗?

The map function takes the data that the Observable got, processes it using the function that was supplied to it and returns a new Observable. map函数获取Observable获得的数据,使用提供给它的函数对其进行处理,然后返回一个新的Observable。 You still need to subscribe to this new Observable to start the process. 您仍然需要订阅此新的Observable才能开始该过程。

In your example, the Observable will return only one response. 在您的示例中,Observable将仅返回一个响应。 the map function will take this response and convert it to either undefined if its status is 204 or to the contained json otherwise. map函数将获取此响应,如果状态为204,则将其转换为undefined,否则将其转换为所包含的json。

To use it from outside this class: 要在此类之外使用它:

class TestClass {
    constructor(private usersApi: UsersApi ) {}

    public testFunction() {
        this.userApi.create("user", "pass").subscribe(
            (result: any) => {       // <-- handler for result
                console.log(result);
            },
            (error: any) => {        // <-- handler for error
                console.log(error);
            },
            () => {                  // <-- handler for done
                console.log("Done");
            },
        );
    }
}

map() just transforms stream event values. map()只是转换流事件值。
You get an event value from the stream passed as parameter, can do some transformation like response.json() , and the result is the new event value for following operators or subscribe() 您可以从作为参数传递的流中获取事件值,可以进行一些转换(例如response.json() ,结果是以下运算符或subscribe()的新事件值

Without subscribe() nothing will happen. 没有subscribe(),将不会发生任何事情。 If you don't subscribe, http.get() will not result in a request to the server. 如果您不订阅,http.get()将不会导致对服务器的请求。

If you use the | 如果使用| async pipe, then you don't need to subscribe yourself. 异步管道,则您无需订阅。 The pipe does it for you 管子帮你做

You need to subscribe an Observable function to actually execute a service. 您需要subscribe一个Observable函数才能实际执行服务。

UserApi.create(user, password).subscribe(
   res=> {//do stuffs that have remote data "res" here},
   error=> {//do what when "error" happens},
   () => console.log('Completed!')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM