A
A
Alexander Mikhailenko2018-03-11 17:44:01
Angular
Alexander Mikhailenko, 2018-03-11 17:44:01

How to wait for a response from a service in Angular 2?

Good afternoon. I am a beginner in angular, so some points may not be clear. I will be glad for any help.
The question is how to wait for a response from the service and only then continue the work of the component.
I have a component in which, on a click event, a request is made to a service, which, in turn, makes a post request to the google api. But the problem is that immediately after sending a request to the service, the code continues to be executed further and my variable does not get the value that appeared in the service.
The makeShort() method, it works only on clicking on the button in the layout, and this is the only way it should be.
Here is the cat of the component:

import { Component } from "@angular/core";
import { ShortenerService } from "../../shared/shortener.service";

let utm = {
    source: 'google',
    medium: 'cpc',
    campaign: '{campaignid}'
};

@Component({
    selector: "my-google",
    templateUrl: "google.component.html",
})
export class GoogleComponent {
    utmSource: string = utm.source;
    utmMedium: string = utm.medium;
    utmCampaign: string = utm.campaign;
    utmContent: string = '';
    utmTerm: string = '';
    resultUtm: string = '';
    utmUrl: string = '';
    shortUrl: string = '';
    FlushMessage: any = '';
    errorMessage: String;

    changeUtm(type:string,event:any) {
        //console.log(event.target.value + "=" + type);
        let results = this.utmUrl+'?utm_source='+this.utmSource+'&utm_medium='+this.utmMedium+'&utm_campaign='+this.utmCampaign; 
        if(this.utmContent != '') {
            results += '&utm_content='+this.utmContent;
        }
        if(this.utmTerm != '') {
            results += '&utm_term='+this.utmTerm;
        }
        
        //console.log(this.ShortenerService.getData());
        this.resultUtm = results;
    }

    reset() {
        this.utmSource = utm.source;
        this.utmMedium = utm.medium;
        this.utmCampaign = utm.campaign;
        this.utmUrl = '';
        this.utmContent = '';
        this.utmTerm = '';

        this.resultUtm = this.utmUrl+'?utm_source='+this.utmSource+'&utm_medium='+this.utmMedium+'&utm_campaign='+this.utmCampaign; 
    }

    makeShort() {
       
        let resultObj : any;
        let test: any;

        this.ShortenerService.urlShortener(this.resultUtm).subscribe(
            result => test = result,
            error => this.errorMessage = error
        );   
       
        //console.log(resultObj);
        console.log(test);
        console.log('2222');
    
        // if(resultObj.id !== undefined) {
        //     this.FlushMessage = resultObj.id; 
        // } else {
        //     this.FlushMessage = resultObj.error.message;
        // }
    }

     constructor(private ShortenerService: ShortenerService) {}
    
}

and here is the service code
import { Injectable } from '@angular/core';
import {Http, Response, Request, HttpModule} from '@angular/http';
import {Observable}              from 'rxjs/Observable';
// Observable class extensions
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';

// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class ShortenerService {
   
    result:any = '';

    constructor(private http: Http  ) { }

     urlShortener(longUrl: string): Observable<any> {
        let body = {longUrl: longUrl}
    
    
        let options = {
            params: {key: 'AIzaSyDz3CSxjs2fTm9V-No0A15NCr1cxz2icxs'},
        };

        return this.http.post('https://www.googleapis.com/urlshortener/v1/url', body, options)
        // .subscribe(
        //     result => {
        //         this.result = result.json();
        //       },
        //       error => {
        //           this.result = JSON.parse(error._body);  
        //       },
        //       () => {
        //         console.log('Request complete');
        //       }
        // );
        .map(this.extractData)
        .catch(this.handleError);

      
        //return true;
 
        //return this.result;
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        //console.log(errMsg);
       console.log(error);
       console.log('1111');
        //errMsg = JSON.parse(error._body);
        //console.log(errMsg);
        return Observable.throw(errMsg);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2018-03-11
@m1hasik

work with result inside subscribe

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question