Kostas_Me_
Kostas_Me_

Reputation: 113

Angular 2 - Setting Timeout in a Service

I want to create a delay in a Service of my Angular 2 project for testing purposes. More specifically, I want the call of

this.myIatreioService.getIatreia()

to be delayed for 1 sec. My service is the following:

@Injectable()
export class IatreioService {
   private headers = new Headers();

   constructor(private http: Http) {
       let token = localStorage.getItem('token');
       if (token) {
         this.headers = new Headers({ 'Authorization': 'Bearer ' + token });
       }
   }

   getIatreia(): Observable<Iatreio[]> {
       return this.http
                  .get('http://localhost:3000/iatreia', { headers: this.headers })
                  .map(response => response.json() as Iatreio[]);
   }

} // end of Service

I have tried to implement setTimeout function, but it doesn't work:

getIatreia(): Observable<Iatreio[]> {
   setTimeout(() => {   
      return this.http
                 .get('http://localhost:3000/iatreia', { headers: this.headers })
                 .map(response => response.json() as Iatreio[]);
   }, 1000);
}

Is there a solution for my problem?? If not, can I put setTimeout() either in Component or in Server?? Thank you in advance for your help!

Upvotes: 3

Views: 6625

Answers (3)

Pankaj
Pankaj

Reputation: 29

with httpClient you can do something like:

myService() {
        return this.httpClient.get('http://.to.co/')
            .timeout(200, timeout)
            .map((data) => {
                return data;
            })
            .catch((error: Response) => {
                return (error);
            });
    }

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691775

You can simply use the delay operator:

return this.http
           .get('http://localhost:3000/iatreia', { headers: this.headers })
           .map(response => response.json() as Iatreio[])
           .delay(1000);

Upvotes: 5

Aravind
Aravind

Reputation: 41571

As you are using Observable use the timeout operator as below

return this.http
                 .get('http://localhost:3000/iatreia', { headers: this.headers })
                 .map(response => response.json() as Iatreio[])
                 .timeout(200, 'Timeout has occurred.');

Note: time specified is in milliseconds

Upvotes: 0

Related Questions