angular 5, http.get is ok but http.patch with same parameters returns 404 NOT FOUND - http

I work with Angular 5.
I use a json for data.
I use very often http.get and it always works fine.
But http.patch returns an ERROR 404 NOT FOUND !
Does anybody can explain to me why ?
My config:
Angular CLI: 1.5.0
Node: 6.11.3
OS: win32 x64
Angular: 5.0.0
import { Component, OnInit } from '#angular/core';
import { Constants } from '../shared/classes/constantes/fr/constants';
import { HttpClientModule } from '#angular/common/http';
import { HttpClient } from '#angular/common/http';
import { HttpParams } from '#angular/common/http';
import { Response } from '#angular/http';
#Component({
selector: 'app--test',
templateUrl: './-test.component.html',
styleUrls: ['./-test.component.scss']
})
export class TestComponent implements OnInit {
id: number;
latitude: number;
longitude: number;
constructor(
private http: HttpClient
) {}
ngOnInit() {
this.id = 3;
this.latitude = 44.7637;
this.longitude = -0.5536;
const body = {
'latitude': this.latitude,
'longitude': this.longitude
};
this.http.get(Constants.USERS_URL + '?id=' + this.id).subscribe(data => {
const userLogged = data;
if (!userLogged[0]) {
// NEVER HAPPENS : IT'S OK
} else {
this.http.patch(Constants.USERS_URL + '?id=' + this.id, body).subscribe();
});
}
}

Related

Fetch data from asp.net into highchart

I'm trying to make an application with highchart and asp.net and I followed several tutorials and applications because it's a new thing for me.
But I don't know how to fetch data from asp.net into highcharts.js. I tried to do a getChartData function following one video and then I realised that is for chart.js.Can you give me a idea?
This is my code:
bar-chart.ts
import { Component, OnInit } from '#angular/core';
import * as Highcharts from 'highcharts';
import { SalesDataService } from '../../services/sales-data.service';
import * as moment from 'moment';
#Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent implements OnInit {
constructor(private _salesDataServices:SalesDataService ){}
orders:any;
orderLabels:string[];
orderData:number[];
public barChartLabels:string[];
public barChartData:any[];
title = 'myHighChartsApp';
highcharts = Highcharts;
public options: any ={
chart : {
type: "column"
},
title: {
text: "Monthly Sales Chart Department Wise"
},
xAxis:{
},
yAxis: {
title:{
text:"Sales in Million $"
}
},
series: []
}
ngOnInit() {
}
getChartData(res:Response){
this.orders=res['page']['data'];
const data=this.orders.map(o =>o.total);
const formattedOrders=this.orders.reduce((r,e) => {
r.push([moment(e.placed).format('YY-MM-DD'),e.total]);
return r;
},[]);
const p=[];
console.log('formattedOrders:',formattedOrders);
const chartData=formattedOrders.reduce((r,e)=>{
const key=e[0];
if(!p[key]){
p[key]=e;
r.push(p[key]);
}else {
p[key][1]+=e[1];
}
return r;
},[]);
return chartData;
}
}
sales-data-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs';
import { Order } from '../shared/order';
#Injectable({
providedIn:'root'
})
export class SalesDataService {
constructor(private _http: Http) { }
getOrders( pageIndex: number, pageSize: number
) {
return this._http.get('http://localhost:5103/api/order/'+ pageIndex + '/' + pageSize
)
.map(res => res.json());
}
}

working with FirestoreDocument

I am working with FirestoreDocument and I am trying to retrieving document data.I am getting the post undefined.Below is my code for service and Component
PostService.ts
import { Injectable } from '#angular/core';
import { AngularFirestore,AngularFirestoreCollection,AngularFirestoreDocument} from 'angularfire2/firestore'
import {Post} from './post';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
#Injectable()
export class PostService {
postsCollection: AngularFirestoreCollection<Post>
postDoc: AngularFirestoreDocument<Post>
constructor(private afs:AngularFirestore) {
this.postsCollection = this.afs.collection('posts',ref => ref.orderBy('published','desc'));
}
getPosts(){
return this.postsCollection.snapshotChanges().map(actions=>{
return actions.map(a=>{
const data=a.payload.doc.data() as Post
const id=a.payload.doc.id
return {id, ...data}
})
})
}
getPostData(id: string){
this.postDoc=this.afs.doc<Post>(`posts/${id}`)
return this.postDoc.valueChanges()
}
}
PostDetailComponent.ts
import { PostService } from './../post.service';
import { Component, OnInit } from '#angular/core';
import {ActivatedRoute} from '#angular/router';
import {Post} from '../post';
#Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
post: Post
constructor(
private route:ActivatedRoute,
private postService:PostService
) { }
ngOnInit() {
this.getPost();
console.log(this);
}
getPost(){
const id= this.route.snapshot.paramMap.get('id')
return this.postService.getPostData(id).subscribe(data=>this.post=data)
}
}
PostDetailComponent from console
PostDetailComponent {route: ActivatedRoute, postService: PostService}
post:undefined
postService:PostService {afs: AngularFirestore, postsCollection: AngularFirestoreCollection, postDoc: AngularFirestoreDocument}
route:ActivatedRoute {url: BehaviorSubject, params: BehaviorSubject, queryParams: BehaviorSubject, fragment: BehaviorSubject, data: BehaviorSubject, …}
__proto__:Object
My post from PostDetailComponent is undefined.
The rest of your code looks right, I think it's just that your console.log(this) is in the wrong spot.
ngOnInit() {
this.getPost(); <----- your getPost() function is asynchronous
console.log(this); <----- meaning this console.log runs before you get data from Firebase
so when this runs, posts is still undefined.
If you would console.log(this) *AFTER* you get data
from Firebase, then you should see the values OK.
}
getPost(){
const id= this.route.snapshot.paramMap.get('id')
return this.postService.getPostData(id).subscribe(data=>this.post=data)
^^^^^^^^^^^
ASYNC portion is right here
}
To fix it, move your console.log inside your subscription:
ngOnInit() {
this.getPost();
<--- From here
}
getPost(){
const id= this.route.snapshot.paramMap.get('id')
return this.postService.getPostData(id).subscribe(data=> {
this.post=data;
console.log(this); <--- To here
});
}
EDIT - Additional troubleshooting ref comments below.
getPost(){
const id= this.route.snapshot.paramMap.get('id')
console.log('id from route params is: ' + id); <---- log the *id* too
return this.postService.getPostData(id).subscribe(data=> {
this.post=data;
console.log(data); <--- log *data* instead
});
}
Since angular 6 there were changes on rxjs
// replace import 'rxjs/add/operator/map';
with import { map } from 'rxjs/operators';
Then include .pipe() inside PostService.ts file in getPosts() function
like this:
getPosts() {
return this.postCollection.snapshotChanges().pipe(map(actions => {
return actions.map( a => {
const data = a.payload.doc.data() as Post
const id = a.payload.doc.id
return { id, ...data }
})
})
)
}
Home someone helps, cheers !!!

Angular-Redux Epics

Getting the following error message in console when using the angular-redux library. Also, Redux won't catch or listen for actions after the error occurs. I've searched, including the documentation but nothing points out to fix the error.
Am I missing something?
Error
core.js:1427 ERROR Error: Actions must be plain objects. Use custom middleware for async actions.
at Object.performAction (<anonymous>:3:2312)
at liftAction (<anonymous>:2:27846)
at dispatch (<anonymous>:2:31884)
at eval (createEpicMiddleware.js:67)
at SafeSubscriber.dispatch [as _next] (applyMiddleware.js:35)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)
at Subscriber.next (Subscriber.js:92)
at SwitchMapSubscriber.notifyNext (switchMap.js:127)
Here's code
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { select } from '#angular-redux/store';
import { ScheduleActions } from '../store/actions'
#Component({
selector: 'app-page2',
templateUrl: './page2.component.html',
styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit {
#select(['schedule', 'scheduleList']) values: any;
constructor(public actions: ScheduleActions) { }
ngOnInit() {
this.actions.loadSchedule();
}
}
Actions
//schedule-actions.ts
import { Injectable } from '#angular/core';
import { NgRedux } from '#angular-redux/store';
import { Schedule } from '../../model/schedule.model';
#Injectable()
export class ScheduleActions {
static readonly LOAD_SCHEDULE = 'LOAD_SCHEDULE';
static readonly LOAD_SCHEDULE_SUCCESS = 'LOAD_SCHEDULE_SUCCESS';
constructor(private ngRedux: NgRedux<any>){}
loadSchedule(){
this.ngRedux.dispatch({
type: ScheduleActions.LOAD_SCHEDULE
});
}
}
Reducer
//schedule-reducer.ts
import { ScheduleActions } from '../actions';
export interface SCHEDULE_STATE {
scheduleList: any,
scheduleDetail: any
}
const initialState: SCHEDULE_STATE = {
scheduleList: [],
scheduleDetail: {}
}
export const ScheduleReducer = (state: SCHEDULE_STATE = initialState, action): SCHEDULE_STATE => {
switch(action.type){
case ScheduleActions.LOAD_SCHEDULE_SUCCESS:
return {...state, scheduleList: action.payload };
case ScheduleActions.LOAD_SCHEDULE_DETAIL_SUCCESS:
return {...state, scheduleList: action.payload };
case ScheduleActions.CREATE_SCHEDULE_SUCCESS:
return {...state, scheduleDetail: action.payload };
default:
return state;
}
}
Epics
//schedule-epic.ts
import { Injectable } from '#angular/core';
import { ActionsObservable, ofType } from 'redux-observable';
import { ScheduleService } from '../services';
import { ScheduleActions } from '../actions';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class ScheduleEpic {
constructor(private service: ScheduleService,
private actions: ScheduleActions
){}
loadScheduleEpic = (action$: ActionsObservable<any>) => {
return action$.ofType(ScheduleActions.LOAD_SCHEDULE)
.mergeMap(action => {
return this.service.loadSchedule().map(result => {
this.actions.loadScheduleSuccess(result)
})
})
}
}
Service
//schedule-service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Schedule } from '../../model/schedule.model';
#Injectable()
export class ScheduleService {
private API_URL: String = "http://mockserver.io/v2";
constructor(private http: HttpClient){}
loadSchedule(){
return this.http.get(this.API_URL + '/5a6225153100004f2bde7f27').map(res => res)
}
}
That error means you dispatched something that was not an action--in this case, your epic emitted something that wasn't an action.
Thankfully, it's an easy fix! You're just missing a return statement in your map
return this.service.loadSchedule().map(result => {
this.actions.loadScheduleSuccess(result)
})
// change it to this:
return this.service.loadSchedule().map(result => {
return this.actions.loadScheduleSuccess(result)
})

Unable to broadcast messages from http extender class to App Component in Angular 2

project Structure
Error Information
This is the error i am getting , when i broadcast the message from http extender service to the app component.
Loading Interceptor(http extender)
this is my http extender ,i am unable to broadcast the messages to App component from here ,but i am able to broadcast the messages from the child components to App component ,please see the image for the error information and project structure
import { Injectable } from '#angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { EventsEmitter } from './eventsEmitter';
#Injectable()
export class LoadingInterceptor extends Http {
private currentRequests: number = 0;
public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private eventsEmitter: EventsEmitter) {
super(_backend, _defaultOptions);
}
public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.incrementRequestCount();
var response = super.get(url, options);
response.subscribe(null, error => {
this.decrementRequestCount();
}, () => {
this.decrementRequestCount();
});
return response;
}
private decrementRequestCount() {
if (--this.currentRequests == 0) {
this.eventsEmitter.broadcast('loading-complete');
}
}
private incrementRequestCount() {
if (this.currentRequests++ == 0) {
this.eventsEmitter.broadcast('loading-started');
}
}
}
App Component
I am listening the events broadcasted in the app component to show the loader gif on the screen
import { Component } from '#angular/core';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterService } from 'angular2-toaster';
#Component({
selector: 'my-app',
templateUrl:'app/app.component.html'
})
export class AppComponent {
private toasterService: ToasterService;
private message: any;
private active: any;
constructor(toasterService: ToasterService, private eventsEmitter: EventsEmitter) {
this.toasterService = toasterService;
this.eventListners();
}
eventListners() {
this.eventsEmitter.on<string>('loading-complete')
.subscribe(message => {
this.active = false;
});
this.eventsEmitter.on<string>('loading-started')
.subscribe(message => {
this.active = true;
});
}
}
Event Emitter
this is the event emittter i am using to broadcast the events
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
interface EventsEmitterInterface {
key: any;
data?: any;
}
export class EventsEmitter {
private _eventBus: Subject<EventsEmitterInterface>;
constructor() {
this._eventBus = new Subject<EventsEmitterInterface>();
}
broadcast(key: any, data?: any) {
this._eventBus.next({ key, data });
}
on<T>(key: any): Observable<T> {
return this._eventBus.asObservable()
.filter(event => event.key === key)
.map(event => <T>event.data);
}
}
App Module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { HttpModule, JsonpModule, Http, RequestOptions, XHRBackend, RequestOptionsArgs, Response, ConnectionBackend} from '#angular/http';
import { AppRoutingModule } from './app.routes';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { LoadingInterceptor } from './assets/scripts/services/loadingInterceptor';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterModule, ToasterService } from 'angular2-toaster';
#NgModule({
imports: [AppRoutingModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, JsonpModule, ToasterModule ],
declarations: [AppComponent, LoginComponent],
bootstrap: [AppComponent],
providers: [EventsEmitter,LoadingInterceptor,
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, eventsEmitter: EventsEmitter) => new LoadingInterceptor(xhrBackend, requestOptions, eventsEmitter),
deps: [XHRBackend, RequestOptions]
},{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppModule { }
I am stuck here for many days, it would be really helpful if you could help me resolve this issue
You forgot to add EventsEmitter dependency within your useFactory provider:
deps: [XHRBackend, RequestOptions]
It shoul be:
deps: [XHRBackend, RequestOptions, EventsEmitter]
That's why your LoadingInterceptor constructor gets undefined for EventsEmitter dependency

Angular 2 cannot read property 'get' of undefined

I have seen this error on SO quite a few times, all I can find on it is that I need to make sure that I have my service Provided in my app.modules, and then call it in my constructor of my component. I have done this and am still getting the error. Also I have both http and HTTPMODULES in my application. The error only occurs when I use the delete functionality in my application. Here is the error error_handler.js:45 EXCEPTION: Cannot read property 'get' of undefined, here is some relevant code....
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule, JsonpModule } from '#angular/http'; <------------HTTP
import { AppComponent } from './app.component';
import { PostRantComponent } from './postRant.component';
import { PostDataService } from './PostData.Service'; <------------service
import { Constants } from './app.const.service';
import { Routing } from './app.routes';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [NgbModule.forRoot(), BrowserModule, Routing, FormsModule, HttpModule, JsonpModule],
declarations: [AppComponent,,PostRantComponent],
providers: [PostDataService, Constants],
bootstrap: [AppComponent]
})
export class AppModule { }
Service (tried cutting it down to just show relevant code)
import { Injectable } from '#angular/core';
import { Http, Response, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import { PostViewModel } from './models/Post';
import { Constants } from './app.const.service';
#Injectable()
export class PostDataService{
private actionUrl: string;
private headers: Headers;
constructor( private _http: Http, private _constants: Constants ){
this.actionUrl = _constants.ServerWithApi;
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept','application/json');
}
public GetAll = (): Observable<PostViewModel[]> => {
return this._http.get(this.actionUrl)
.map((response: Response) => <PostViewModel[]>response.json())
.catch(this.handleError);
}
public Delete = (id: string) =>{
return this._http.delete(this.actionUrl + id)
.map(res => res.json())
.catch(this.handleError);
}
}
Component
import { Component, Attribute, OnInit,ViewChild } from '#angular/core';
import { PostViewModel } from './models/Post';
import { PostDataService } from './PostData.Service';
import { Constants } from './app.const.service';
#Component({
selector: 'postRant',
templateUrl: 'html/postRant.html',
})
export class PostRantComponent implements OnInit {
txtTitle: string;
txtDescription: string;
public myPosts : Array<PostViewModel>;
public newPost : PostViewModel = new PostViewModel();
constructor(private auth:Auth, private _dataservice: PostDataService){
}
ngOnInit(){
this.getAllItems();
}
private getAllItems():void {
this._dataservice
.GetAll()
.subscribe((Post: Array<PostViewModel>) => this.myPosts = Post,
error => console.log(error),
() => console.log('get all items complete'))
}
delete(id){
console.log(id);
this._dataservice.Delete(id)
.subscribe((res) => {
this.myPosts = res;
});
var index = this.myPosts.findIndex(x => x.id == id);
this.myPosts.splice(index, 1);
}
}
If you are interested in all the code I have it posted on my git located here, however it is rather large.
EDIT
picture of error....
it appears that the error is produced by line 52 of PostData.Service.ts
i.e. var applicationError = error.headers.get('Application-Error');
this makes me guess that your GetAll Http call is erroring out, but the server you are asking for data is not returning data in the format of error.headers
Add a debugger; to the handleError and check the object that it is receiving.

Resources