Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  159] [ 7]  / answers: 1 / hits: 21993  / 9 Years ago, sat, december 5, 2015, 12:00:00

I have service defined in Angular 2 like this:



import { Inject } from 'angular2/angular2';
import { Http ,Headers , HTTP_PROVIDERS } from 'angular2/http';

export interface CourseInterface {
courseId: number,
coursePrice: number,
authorName: string
}

export class CourseDetailsService {
http: Http;
constructor(@Inject(Http) Http) {
console.log(Http)
this.http = Http;
}

load() {
console.log(came here in service)
var headers = new Headers();
headers.append('Authorization', <my username password>);

this.http.get('https://some.api',{
headers : headers
}).map(res => console.log(Response came!!!))

console.log(done . . .)
}
}


and in another component, I use this service like this:



import {CourseInterface, CourseDetailsService} from '../services/course';

@Component({
selector: 'dashboard',
viewBindings: [CourseDetailsService]
})
@View({
template: `
<h1>Dashboard page laoded</h1>
`
})
export class Dashboard {
constructor(service: CourseDetailsService) {
service.load();
}
}


and while running the application, I can see my Dashboard component gets displayed on the screen. But however from the CourseDetailsService, no http calls are getting fired.



But in the console I could able to see the following printed:



came here in service
done . . . .


But in my chrome networks tab, I couldn't able to see any request fired to the specified url. Where I am making mistake?



I'm using Angular 2 Alpha 47


More From » angular

 Answers
15

Basically the part that triggers the request itself it's the subscribe, so to make it work you have to add it.



// Service
load() {
var headers = new Headers();
headers.append('Authorization', <my username password>);

return this.http.get('https://some.api',{
headers : headers
}).map(res => console.log(Response came!!!))
}

// Component
// 'subscribe' triggers the request!
service.load().subscribe((result) => /* do something with result */);

[#64154] Wednesday, December 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;