简体   繁体   中英

RxJs Observables and http angular2 service

I know there's a lot of tutorials over there about how to use 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.

Up to now, I've able to generate a service in order to get communication with a REST endpoint:

@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.

How would I need to use UserApi.create(user, password) method?

EDIT

Since http.get(...) method isn't going to be performed without a subscription , I figure out I need any stuff like:

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

Could somebody fill up subscribe method?

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. You still need to subscribe to this new Observable to start the process.

In your example, the Observable will return only one response. the map function will take this response and convert it to either undefined if its status is 204 or to the contained json otherwise.

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.
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()

Without subscribe() nothing will happen. If you don't subscribe, http.get() will not result in a request to the server.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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