get the data from the server in Angular5


get the data from the server in Angular5



How to get the data from Server using Angular5.
i want to about Get call in Angular5



i tried this:


getField (): Observable<b_fld> {
return this.http.get<fld>(this.fieldUrl)
.pipe(
tap(fields => console.log(`fetched fields`))
);
}




1 Answer
1



The way I do it is.
This is my service.ts set up.


service.ts


import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';



Import the HttpClient and HttpHeaders and then set them up like below


HttpClient


HttpHeaders


accessToken;
apiUrl = environment.apiUrl; // Url Reads http://my-api.com

// Only Needed if you have headers
headers = new HttpHeaders()
.set('Authorization', this.accessToken);

constructor(
private http: HttpClient
) { }

getMyData(): Observable<any> {
return this.http.get(
this.apiUrl + '/my-data', // Url Reads http://my-api.com/my-data
{headers: this.headers} // Include Headers If needed
);
}



Then inside my compoinent.ts file look like this.


compoinent.ts



import { MyService } from '../../services/my.service';


import { MyService } from '../../services/my.service';


...
data;
...

constructor(
...
private myService: MyService
...
) { }

async ngOnInit() {
try {
await this.getData();
} catch (error) {
console.log(error);
}
this.loaded = true;
}

async getData() {
this.data = await this.getMyData();
}

// Get the Data
getMyData() {
return new Promise((resolve, reject) => {
this.myService.getMyData()
.subscribe(
data => {
resolve(data);
}, err => {
reject(err);
}
);
});
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages