1

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?

1

3 Answers 3

2

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");
            },
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

5 Comments

Do I need subscribe method? Could you provide a very simple straightforward stuff using UserApi?
Your example already looks like s simple straightforward example. Without subscribe() nothing will happen. If you don't subscribe, http.get() will not result in a request to the server. I don't know what you mean by UserApi. Did you check angular.io/docs/ts/latest/tutorial/toh-pt6.html?
If you use the | async pipe, then you don't need to subscribe yourself. The pipe does it for you.
It seems good. Nevertheless, I have no idea what's that. Any sample or documentation page?
1

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!')
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.