I am calling HTTPS API from Angular service deployed in http server by the following code.
this.chatbotUrl = "https://something.com/api";
getDashBoardData(): Observable<any> {
return this.http.get<IContainer>(this.chatbotUrl+"/chatbot/get-dashboard-data").pipe(
map((response) => (response ? response : {})),
catchError( this.handleError )
);
}
But when I am calling this API, then I am getting this error, "Http failure response for https://something.com/api/chatbot/get-dashboard-data: 0 Unknown Error". The following error is also get.
GET https://something.com/api/chatbot/get-time-wise-traffic/7 net::ERR_CERT_COMMON_NAME_INVALID
How can I call https API from Angular service deployed in http server?
I suppose you have not configured the API properly,check whether the site requires any key to get accessed.Here I have provided the component.ts file and service file for the API I am working with for your reference.
If CORS error try adding CORS extension to your browser;else clear your cache and run your code again.
Component.ts:
import { Component, OnInit } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
import { YoutubeService } from '../youtube.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
Name:any;
details: any;
info:any;
display!:boolean;
constructor(private service:YoutubeService,public sanitizer: DomSanitizer) { }
ngOnInit(): void {
this.service.GetVideos().subscribe((res:any)=> {
this.info= res as any
this.info=this.info.items;
console.log(this.info);
this.display=true
});
}
onSubmit() {
this.service.GetSearch(this.Name).subscribe(res=> {
this.details= res as any
this.details=this.details.items;
// this.details.forEach((function.this.details.i) => {
// ele
// });
console.log(this.details);
this.display=true
});
}
}
Service:
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { GoogleLoginProvider } from 'angularx-social-login';
#Injectable({
providedIn: 'root'
})
export class YoutubeService {
private APIURL = "https://youtube.googleapis.com/youtube/v3/";
private APIKEY ="AIzaSyB40HaKwd0VggftBq8R9sEwQx_NG5xOOWc";
constructor(private http:HttpClient) { }
public GetSearch(name:string)
{
console.log(name)
return this.http.get(this.APIURL+"search?part=snippet&key="+this.APIKEY+"&q="+name+"&type=video");
}
Related
I am completely unfamiliar with the angular since I am a back-end developer. To test my api, I need to send an ajax request from angular.
Tell me how to do this?
There is a code. The request must be executed before clearing the localeStorage.
<button (click)="logoutAndClose()" class="btn_green btn_ml" mat-raised-button>
Log out
</button>
#Component({
selector: 'app-logout-modal',
templateUrl: './logout-modal.component.html',
styleUrls: ['./logout-modal.component.scss']
})
export class LogoutModalComponent implements OnInit {
constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>,
private router: Router,
private http: HttpClient,
#Inject(MAT_DIALOG_DATA) public data: any) {
}
ngOnInit() {
}
logoutAndClose(): void {
this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
localStorage.clear();
this.thisDialogRef.close();
this.router.navigateByUrl(RouteUrls.Login);
}
}
As a best practice you should create a service to send HTTP requests:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class YourService {
private url: string = "http://api";
private endpoint:string = "car";
constructor(private http: HttpClient,
) { }
get(id: number): Observable<Car> {
return this.httpClient
.get<Car>(`${this.url}/${this.endpoint}/${id}`)
.pipe(map(data => data));
}
}
and then you will be available to use built in dependency injection in your component:
export class YourCarComponent {
constructor(private yourService: YourService) {
}
getCars(id: number) {
this.yourService.get(id)
.subscribe(s=> console.log(s));
}
UPDATE:
In order to execute your http query, you need to run it. So you need to call subscribe method:
this.http.post("http://127.0.0.1:8001/api/v1/users/settings/logout/")
.subscribe(s => console.log(s));
In addition, as a best practice should not contain an implementation details of http requests because it is not deal of view. View should just show data.
You need to import the HTTPModule
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
Inject inside constructor:
#Injectable()
export class YourService {
constructor(private http: HttpClient) { }
}
this.http.get(this.url).subscribe((data: CanBeDirectlyMapToJsonObject) => {
});
For More details refer to https://angular.io/guide/http
I have an Angular 7 project with a PHP Laravel API backend that is returning json from get requests.
return Response::json($genres);
I'm using httpClient in a service which is being called from a component (see both below). When I console log the data it is a string, not a json object. Also I am unable to access any of the properties that it has because it is just a long string.
In most online examples people used map and then pipe but those are both deprecated now and apparently httpClient just returns JSON as default but that is not what appears to be happening in this case.
Could someone give me a solution to this? I need access to the data in the response as JSON.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http:HttpClient) { }
getGenres(){
return this.http.get('http://www.localhost:7888/api/genres', this.genre);
}
}
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../../services/api.service';
#Component({
selector: 'app-genres',
templateUrl: './genres.component.html',
styleUrls: ['./genres.component.css']
})
export class GenresComponent implements OnInit {
constructor(private apiService: ApiService) { }
ngOnInit() {
// make http request to http://www.localhost:7888/api/genres
this.apiService.getGenres().subscribe(data => {
console.log(data);
},
error => {
console.log(error);
});
}
}
I am trying to work with REST API's provided within my Enterprise Application and Angular. What I am trying to achieve is to fetch some data from my Enterprise Application. For this I have to do two things:
1- Login to my Enterprise Application via Angular. For doing so, there's already a custom authentication REST API provided by the Enterprise Application. I am consuming the same. An authentication token is generated which I am saving within localStorage.
2- Send a GET request to the Enterprise Application to fetch data after Authentication happened. This is where I am facing issues. I am unable to pass the authentication token within the GET Request. On Checking the same under "Application" Tab of Chrome Dev Tools, I Could see under "Request Headers" Section that Authorization value is null. Below is the screenshot of the same:
Below is my code that I have developed:
1 - Authentication Service (auth.service.ts)
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import{Http} from '#angular/http'
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { URLSearchParams,Response } from '#angular/http'
#Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
username:string = 'Admin';
password:string='livelink';
token:any;
login()
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('Username', this.username);
urlSearchParams.append('Password', this.password);
this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
.subscribe((res:Response) =>
{
// login successful if there's a jwt token in the response
if (res) {
const data = res.json();
;
this.token = data;
console.log(data);
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
}
});
console.log("INSIDE LOGIN this.token = "+this.token)//done for debugging, returning undefined
}
public getToken()
{
console.log("GET TOKEN VALUE "+ localStorage.getItem('ticket'))//done for debugging, returning undefined
return localStorage.getItem('ticket');
}
}
2 - Token Interceptor (token.interceptor.ts)
import { Injectable } from '#angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { AuthenticationService } from './auth.service';
import { Observable } from 'rxjs';
import { Http } from '#angular/http';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
3 - App Component (app.component.ts)
import { Component } from '#angular/core';
import { AuthenticationService } from './auth.service';
import{Http} from '#angular/http'
import { HttpClient } from '#angular/common/http'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
constructor(private authenticationService: AuthenticationService, private
http:HttpClient)
{
this.authenticationService.login();
this.ping() ;
}
public ping() {
this.http.get('http://localhost/otcs/cs.exe/api/v1/nodes/16236/output')
.subscribe(
data => console.log(data),
err => console.log(err)
);
}
}
4- App Module (app.module.ts)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from
'#angular/common/http';
import { AppComponent } from './app.component';
import { AuthenticationService } from './auth.service';
import { HttpModule } from '#angular/http';
import { TokenInterceptor } from './token.interceptor';
#NgModule({
declarations:[AppComponent],
imports: [
BrowserModule,
HttpClientModule,
HttpModule
],
providers: [AuthenticationService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
On running the above project, below is the output displayed in Console:
I am unable to understand as to why is my token not getting passed with the GET Request.
You are saving the token using this line
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
But, your function getToken() is getting it wrong from localStorage. I think your function should look like:
public getToken() {
const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
console.log("GET TOKEN VALUE ", currentUser.ticket))//done for debugging
return currentUser.ticket;
}
Hope it helps
While retrieving the token in getToken, use the key as "currrentUser" instead of "ticket"
public getToken() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
return currentUser.ticket;
} else return null;
}
Better to store the key in some config so its accessible everywhere hence no missing on current key.
I am using Angular 5 and trying to get some data from JsonPlaceholder.
First I created the service, then added:
import { HttpClientModule } from '#angular/common/http';
This is the service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'http://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
this.http.get(`${this.ROOT_URL}/posts`).subscribe(data => {
return data;
});
}
}
And finally, on my app.component.ts:
import { Component, OnInit } from '#angular/core';
import { DataService } from '../../services/data.service';
#Component({
selector: 'app-root',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {
data;
constructor(private dataService: DataService) {
this.data = dataService.getPosts();
console.log(this.data;
}
ngOnInit() {
}
}
On the console it's just returning 'Undefined'
What I'm I doing wrong?
Don't subscribe on the service, return the observable and subscribe to it on the component. Because it is asynchronous your data variable on the component will be undefined because you assigned before the http request could resolve a value.
On the service:
getPosts() {
return this.http.get(`${this.ROOT_URL}/posts`);
}
On the coponent:
ngOnInit() {
this.dataService.getPosts().subscribe(posts => this.posts = posts);
}
Try following code snippet.
You are getting undefined because you assigning the data before the http request could resolve a value. Remove the subscription from service and move it to component.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get(`${this.ROOT_URL}/posts`);
}
}
AppComponent.ts
import { Component } from '#angular/core';
import {DataService} from './data.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(public data:DataService){
this.data.getPosts().subscribe(data=>{
console.log(data);
})
}
}
See the Demo here
import { HttpClientModule } from '#angular/common/http';
//This is the service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'http://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
//if you want to use the observable which returns from .get()
//.. you need to do "return"
return this.http.get(`${this.ROOT_URL}/posts`);
}
}
//app.component.ts:
import { Component, OnInit } from '#angular/core';
import { DataService } from '../../services/data.service';
#Component({
selector: 'app-root',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {
data;
constructor(private dataService: DataService) {
this.data = dataService.getPosts();
//so if you want to use the value of your http call outside..
//..of the service here is a good place where to do subscribe()
this.data.subscribe(data => {
console.log(this.data;
});
}
ngOnInit() {
}
}
You expect a return value and returns nothing. Your return statement is placed inside a nested-lambda function, thus using "return" in the place you used it causes the inner function to return a value, and not the outer one as you needed.
I suggest you to read about asynchronous programming, and particularly about Observable (which works on the same concept of Promise) in Angular.
I basically agree to #Eduardo Vargas answer, but it might be also a good idea to do it in resolver, which will call api, and put data into route snapshot. Thanks to this it won't wait on empty page for loading the data on subscribe in constructor. More info here:
https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html
Hi i'm new in Angular 4 and I want to use it to build a WordPress theme using the wp-api. I start with the ng-wp-theme but I and all its working fine, but I need that hen a new post is publish the post list page updates itself without reload the page. I saw some tutorials about the http services in angular but I dont find any solution to this, maybe its a Wordpress api issue and not the Angular part.
here is the service:
import { Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Observable } from 'rxjs/Observable';
import { Post } from './post';
import { environment } from '../../environments/environment';
#Injectable()
export class PostsService {
private _wpBase = environment.wpBase;
constructor(private http: HttpClient) { }
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + 'posts');
}
getPost(slug: string): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + `posts?slug=${slug}`);
}
}
and the controller:
import { Component, OnInit } from '#angular/core';
import { Post } from '../post';
import { PostsService } from '../posts.service';
import { Router } from '#angular/router';
import { HttpErrorResponse } from '#angular/common/http';
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
providers: [PostsService]
})
export class PostListComponent implements OnInit {
public posts: Post[];
constructor( private postsService: PostsService, private router: Router ) {}
ngOnInit() {
this.postsService.getPosts().subscribe(
(posts: Post[]) => this.posts = posts,
(err: HttpErrorResponse) => err.error instanceof Error ? console.log('An error occurred:', err.error.message) : console.log(`Backend returned code ${err.status}, body was: ${err.error}`));
}
selectPost(slug) {
this.router.navigate([slug]);
}
}