Angular 6 - externalizing url - javascript

I am trying to externalize the url and proerties in angular 6.
Have a service which invokes 3rd party URL to get data.
weather-component.html -> weather.component.ts -> weather.service.ts
In my weather.service.ts,
public getWeather() {
// Here I have hardoded the URL and the api key.
}
I would like to externalize this so as to make it configurable.
Not sure how to move it to a configurable file and read from there.

Exactly the same manish's answer but when we started the project in Angular 2 , this blog had been quite helpful. Over the upgrades over http gateway has changed massively and it was very useful when angular changed the httpclient in 4 .
https://blog.sstorie.com/adapting-ben-nadels-apigateway-to-pure-typescript
Also if you are looking for a place to put base url etc , I would use the environment ts file in angular-cli
https://github.com/angular/angular-cli/wiki/stories-application-environments

I suppose you want to make generic service
you can have a baseHttp.service.ts and weather.service.ts will extend the baseHttpservice to make the api calls.
baseHttp.service.ts
#Injectable()
export abstract class BaseHttpService {
private baseUrl: string = Constants.BASEURL;
protected method: string;
protected serviceUrl: string;
protected headers: Headers;
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
call(params: any) {
let url: string = this.setUrl();
let options = new RequestOptions({ headers: this.headers });
options.url = url;
options.method = this.method;
options.body = params;
return this.http.request(url, options).toPromise()
.then((response: any) => this.extractData(response))
.catch((error: any) => this.handleError(error));
}
//complete the other functions
}
weather.service.ts
#Injectable()
export class DashboardService extends BaseHttpService {
constructor(private _http: Http) {
super(_http);
}
getWeatherReport(params:any) {
this.serviceUrl = 'some-url';
this.method = "GET";
return super.call(params);
}
}
so you can inject weather.service.ts and override the values in weather.service.ts and make http calls
so baseHttp.service.ts acts as a interceptor, so you can intercept all the Http calls there.

Related

Angular, add a post ajax call directly into an angular service

I have some old code which does ajax calls. I wrote a new angular 10 application, which needs to run the original ajax code directly into the angular service (per requirement). Is there a way to run an ajax call directly or a node module that can be used. Thanks for the help.
#Injectable({providedIn: 'root'})
export class SomeService {
destroy$ = new Subject();
constructor(private http: HttpClient) { }
ajax(): Observable<DataType> {
return this.http
.get<DataType>(URL, {params: {email: 'tt#tt.tt'}})
.pipe(
takeUntil(this.destroy$), // will unsubscribe automatically if call this.destroy$.next(true) && this.destroy$.complete()
map(data => /*map data here if need*/)
);
}
}

angular http client is not working when calling node backend locally?

Trying to call nodejs local host using angular http client but it is not hitting the backend i have added url in the proxy.config in angular app as i added in the question that doesnt work either any idea ?
angular service.ts
import { Injectable } from '#angular/core';
import { HttpClient , HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({providedIn: 'root'})
export class AdminService {
constructor(private http: HttpClient) { }
private url = "http://localhost:9001/api/saveClients";
saveClientJobs(data) {
let options = this.createRequestOptions();
console.log("Service", data);
return this.http.post(this.url, data, { headers: options });
}
private createRequestOptions() {
let headers = new HttpHeaders({
"Content-Type": "application/json"
});
return headers;
}
}
angular proxy.config.json
{
"/api/*":{
"target":"http://localhost:9001",
"secure":false,
"logLevel":"debug",
"changeOrigin": true
}
}
NodeJs routes
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const admin_controller_1 = require("./api/admin/admin.controller");
class RegisterRouteClass {
RegisterRoutes(app) {
app.post('/api/saveClients', admin_controller_1.AdminController.save);
}
}
exports.RegisterRouteClass = RegisterRouteClass;
In order for a post/get to be executed you need to subscribe to it. If you are not subscribing to the post/get, it will never execute thus nothing will be output in the network tab of the developer tools.
saveClientJobs(data).subscribe(result => /* do something with the result */)

Values from web api are not being converted

I have a web api call. The property of checkNumber is a double on the web api side , however in my typescript model I need it to come in as a string. It is staying as a number even though my model clearly has it as a string variable.
Is there a way to get the conversion to automatically happen to string?
my web api call
public GetMyClass(myModel: MyClass): Observable<MyClass> {
let headers = new HttpHeaders();
headers.append("content-type", "application/json");
headers.append("accept", "application/json");
let options = { headers: headers };
return this.httpClient.post<MyClass>( url, myModel, options)
}
my model
export MyClass{
checkNumber?: string;
}
Typescript doesn't do auto conversion. It helps with type checking during development. At runtime, it just plain javascript.
You will need to define your own conversion.
public GetMyClass(myModel: MyClass): Observable<MyClass> {
let headers = new HttpHeaders();
headers.append("content-type", "application/json");
headers.append("accept", "application/json");
let options = { headers: headers };
return this.httpClient.post<MyClass>( url, myModel, options)
.pipe(
map(dataObject => {
let checkNumber = dataObject.checkNumber
return {
checkNumber: checkNumber ? dataObject.checkNumber.toString() : undefined,
...dataObject
}
})
)
}

Why do I get an old object when creating a new object using let and new in a function within a service?

Alright, simple basic auth authentication service in angular2.
When a user logins first time, it works. But when he/she tries to login second time with a different account. I got double basic auth string in the request headers, it's like "Authorization:Basic YWRtaW46YWJjMTIz,Basic RMcasd9WJjMXoPj".
This is the service:
#Injectable()
export class AuthenticationService {
private url: string = 'http://localhost:8080/api/test';
private username: string;
private password: string;
private authenticationStatus: boolean = false;
constructor(private http: Http) { }
authentication(username: string, password: string): Promise<boolean> {
let headers = new Headers(); // <== previous headers object with old Authorization string get back from grave.
console.log(headers);
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type","application/json;charset=utf-8");
return this.http.get(this.url, { headers: headers })
.toPromise()
.then(response => { ...
This is my first try angular/typescript app. I'm confused by not getting a brand new object when I use both let and new here. Is it because headersString within the header class is static? I did look into the angular headers class api doc. I tried call headers.delete("Authorization"); right after the let headers = new Headers();, The old Authorization header remains.
I'm confused by not getting a brand new object when I use both let and new here.
When you log an object the reference to the object is logged.
As an example:
let x = {};
console.log(foo);
x.foo = 'foo';
Now on your console if you look at x after you've mutated it, it will show the new stuff:
In short. Your code is correct. The console can lie to you.
Alternative answer: You are doing something that is not demonstrated in the code sample you have provided.

Angular JS TypeScript IHttpService inject custom header value

I have a project where I make successful Http Get request from TypeScript (Angular HTTP Service) code to Web API controller and display the list in a grid. The project is using Angular JS 1.4.x and TypeScript successfully.
Full Project's GitHub URL. and the TypeScript code which calls to the server is below.
module App {
export class StudentListService {
private qService: ng.IQService;
private httpService: ng.IHttpService;
constructor($q: ng.IQService, $http: ng.IHttpService) {
this.qService = $q;
this.httpService = $http;
}
get(): ng.IPromise<Object[]> {
var self = this;
var deffered = self.qService.defer();
self.httpService.get('/api/values').then((result: any): void => {
if (result.status === 200) {
deffered.resolve(result.data);
} else {
deffered.reject(result);
}
}, error => {
deffered.reject(error);
});
return deffered.promise;
}
}
StudentListService.$inject = ['$q', '$http'];
angular.module('app').service('StudentListService', StudentListService);
}
Now, I want to add a custom header with the get request call. I have tried many ways, but TypeScript keep giving me build error. Any help or work around would be highly appreciated.
As long as you are using correct typing file for angular you should be able to add header as a part of config, second argument which is of type ng.IRequestShortcutConfig which is an extension of IHttpProviderDefaults that has the header property.
get<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;
Also added much simplified code.
export class StudentListService {
static $inject = ['$q', '$http'];
constructor(private qService: angular.IQService,
private httpService: angular.IHttpService) { }
get(): angular.IPromise<Object[]> {
//Example of config structure
var config: angular.IRequestShortcutConfig = {
headers: {
"someheader":"somevalue"
}
}
//add config and just return the promise directly instead of creating a deferred object. Promises are chainable
return this.httpService.get('/api/values', config)
.then((result: any) => result.data);
//If you want to catch then use ".catch" instead of second argument to the "then" which is a better practice as any error that may happen inside your code in the then block will be caught as well.
}
}

Categories

Resources