Skip to content

Instantly share code, notes, and snippets.

@joeherold
Created June 22, 2016 22:38
Show Gist options
  • Save joeherold/20d9d9f4f13566899198f34b4a741ccb to your computer and use it in GitHub Desktop.
Save joeherold/20d9d9f4f13566899198f34b4a741ccb to your computer and use it in GitHub Desktop.
Observable not updated in Component View
import {Component, OnInit, ChangeDetectorRef, ChangeDetectionStrategy} from "@angular/core";
import {FDB_DIRECTIVES} from "../components";
import {CalendarPipe, DateFormatPipe, TimeAgoPipe, FromUnixPipe} from "angular2-moment/index";
import {OrderByPipe} from "../pipes/order-by.pipe";
import {ResourceService} from "../services/resource.service";
//import {MiniCalendarComponent, CardComponent, CardContentHeaderComponent, AvatarComponent} from "../shared";
declare let jQuery:any;
//directives: [MiniCalendarComponent, CardComponent, AvatarComponent, CardComponent, CardContentHeaderComponent]
@Component({
moduleId: module.id,
selector: 'fdb-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: ['dashboard.component.css'],
//changeDetection: ChangeDetectionStrategy.OnPush,
directives: [FDB_DIRECTIVES],
pipes: [CalendarPipe, DateFormatPipe, TimeAgoPipe, FromUnixPipe, OrderByPipe]
})
export class DashboardComponent implements OnInit {
public items:any[];
constructor(private _prs:ResourceService) {
this.items = [];
}
public ngOnInit():void {
this._prs.stream$.subscribe(
(data) => {
this.items = data;
console.log("#### triggered in console, but not in view represented")
})
this._prs.loadAll();
}
removeItem(id:any) {
this._prs.remove(id);
}
}
import {SailsService} from "./sails.service";
import {Subject} from "rxjs/Rx";
import {Injectable} from "@angular/core";
import {BaseModel} from "./models/basemodel";
// import * as Models from './models/basemodel';
@Injectable()
export class ResourceService {
public _modelURL:string = "/projects";
public _modelClass = BaseModel;
// we declare _todos$ as Subject stream, to be able
// to pass well defined class objects to the observable
// stack
private _subject$:Subject<BaseModel[]>;
// memory datastore to share data across entire application
private dataStore:{
items:BaseModel[]
};
constructor(private _sails:SailsService) {
this.dataStore={
items:[]
};
this._subject$ = new Subject<BaseModel[]>();
this._sails.on("projects").subscribe(msg=>{
console.log(msg);
let found = false;
switch (msg.verb) {
case "updated":
this.dataStore.items.forEach((item, index) => {
// if it is found:
if (item.id == msg.id) {
console.log("should update item");
// we update the data in our memory storage
this.patchItem(index, msg.data);
// and set the notFound flag to false
found = true;
}
});
break;
case "created":
console.log("should add item");
// we are adding it to our collection
this.dataStore.items.push((msg.data));
break;
case "destroyed":
console.log("should delete item");
this.dataStore.items.forEach((item, index) => {
// id's match:
if (item.id == msg.id) {
// we remove the item at the found index
// from our local inmemory dataStore
this.dataStore.items.splice(index, 1);
}
});
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
break;
}
if(found == true) {
this._subject$.next(this.dataStore.items);
}
}, error=>{
});
}
patchItem(index, data){
//console.log("before patch:",this.dataStore.items[index] );
let keys = Object.keys(data);
let temp = this.dataStore.items[index];
for(let key of keys){
temp[key] = data[key];
}
this.dataStore.items[index] = temp;
//console.log("after patch:",this.dataStore.items[index] );
}
// we define a public getter for todos$ stream
// and transform it to a common observable
get stream$() {
// this type of Observable may be bound to a
// template view directly
return this._subject$.asObservable();
}
patchItemData(data){
}
/**
* load all todos
*/
loadAll():void {
this._sails.get(this._modelURL)
// this._http.get(`${this.baseUrl}/todos`, {headers:this.headers})
//
// // we take the passed observable and tell http
// // to map the data as real json objects
// .map(res => res.json())
// .map(this._toTodoObject)
// we subscribe to the http observable, that is
// returned by get and map function and subscribe
// to it, to perform an action when data is
// retieved by the http service with given uri
.subscribe(data => {
//console.log(data);
// fist we update the values of our in memory
// dataStore
let pushData = [];
for (let item of data) {
pushData.push((item));
}
this.dataStore.items = pushData;
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
}, error => {
// in case of an error, we are just logging it
// to the browser console
console.log('Could not create items of type.' + this._modelClass.constructor);
})
}
/**
* load one todo by given id
* @param id
*/
load(model:any):void {
let id = undefined;
if (typeof model == "string" || typeof model == "number" || typeof model == "integer") {
id = model;
} else if (model instanceof BaseModel) {
id = model["id"];
}
this._sails.get(`${this._modelURL}/${id}`)
// we take the passed observable and tell http
// to map the data as real json objects
// .map(res => res.json())
// .map(this._toTodoObject)
// we subscribe to the http observable, that is
// returned by get and map function and subscribe
// to it, to perform an action when data is
// retieved by the http service with given uri
.subscribe(data => {
//console.log(data);
// we define a local variable to check
// if we have to add or update the retieved
// data from the http service
let notFound = true;
// we iterate over the existing data and check
// if this item is already in our collection
this.dataStore.items.forEach((item, index) => {
// if it is found:
if (item.id == data.id) {
// we update the data in our memory storage
this.dataStore.items[index] = (data);
// and set the notFound flag to false
notFound = false;
}
});
// if the item was not found, we will have
// to add it to our collection
if (notFound) {
// we are adding it to our collection
this.dataStore.items.push((data));
}
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
}, error => {
// in case of an error, we are just logging it
// to the browser console
console.log('Could not load item of type.' + this._modelClass.constructor);
})
}
/**
* create an todo item
*
* @param todo
*/
create(model:BaseModel):void {
if (model.id) {
delete model.id;
}
console.log(model.toJSON());
console.log(JSON.stringify(model));
// this._http.post(`${this.baseUrl}/todos`, JSON.stringify(todo), {headers:this.headers})
this._sails.post(this._modelURL, model.toJSON())
// we take the passed observable and tell http
// to map the data as real json objects
// .map(res => res.json())
//.map(this._toTodoObject)
// we subscribe to the http observable, that is
// returned by get and map function and subscribe
// to it, to perform an action when data is
// retieved by the http service with given uri
.subscribe(data => {
// we are pushing (adding) the new retieved data
// to our local inmemory dataStore collection
this.dataStore.items.push((data));
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
}, error => {
// in case of an error, we are just logging it
// to the browser console
console.log('Could not create item of type.' + this._modelClass.constructor);
});
}
update(model:BaseModel):void {
//this._http.put(`${this.baseUrl}/todos/${todo.id}`, JSON.stringify(todo), {headers:this.headers})
this._sails.put(`${this._modelURL}/${model.id}`)
// we take the passed observable and tell http
// to map the data as real json objects
// .map(res => res.json())
//.map(this._toTodoObject)
// we subscribe to the http observable, that is
// returned by get and map function and subscribe
// to it, to perform an action when data is
// retieved by the http service with given uri
.subscribe(data => {
// we iterate over the existing data and check
// the item id to get the index to update the right item
this.dataStore.items.forEach((item, index)=> {
// id's match:
if (item.id == data.id) {
// we are update the right data at
// the right index
this.dataStore.items[index] = (data);
}
});
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
}, error => {
// in case of an error, we are just logging it
// to the browser console
console.log('Could not update item of type.' + this._modelClass.constructor);
})
}
remove(model:any):void {
//this._http.delete(`${this.baseUrl}/todos/${id}`, {headers:this.headers})
let id = undefined;
if (typeof model == "string" || typeof model == "number" || typeof model == "integer") {
id = model;
} else if (model instanceof BaseModel) {
id = model["id"];
}
this._sails.delete(`${this._modelURL}/${id}`)
// we take the passed observable and tell http
// to map the data as real json objects
//.map(res => res.json())
//.map(this._toTodoObject)
// we subscribe to the http observable, that is
// returned by get and map function and subscribe
// to it, to perform an action when data is
// retieved by the http service with given uri
.subscribe(data => {
// we iterate over the existing data and check
// the item id to get the index to remove the right item
this.dataStore.items.forEach((item, index) => {
// id's match:
if (item.id == data.id) {
// we remove the item at the found index
// from our local inmemory dataStore
this.dataStore.items.splice(index, 1);
}
});
// then we publish it to all subscribers
// of the private service property _todos$, that
// can be accessed by the public getter todos$
this._subject$.next(this.dataStore.items);
}, error => {
// in case of an error, we are just logging it
// to the browser console
console.log('Could not remove item of type.' + this._modelClass.constructor);
})
}
// init() {
// this._modelURL = "/projects";
// }
}
import {Injectable} from "@angular/core";
import {Subject, Observable} from "rxjs/Rx";
declare let io:any;
if (io && io.sails) {
if (io && io.socket && io.socket.isConnected) {
io.socket.disconnect();
}
}
interface IJWRes {
body:any;
error?:any;
headers:any;
statusCode:number
}
@Injectable()
export class SailsService {
private _socket:any;
private _connected:boolean = false;
private _opts:any
private _restPrefix:string = "";
private _serverUrl:string;
private _pubsubSubscriptions:any;
constructor() {
this._pubsubSubscriptions = {};
this._opts = {
url: null
};
}
get restPrefix():string {
return this._restPrefix;
}
set restPrefix(value:string) {
if (value.length > 0) {
if (value.charAt((value.length - 1)) == "/") {
value = value.substr(0, value.length - 1);
}
this._restPrefix = value;
}
}
get serverUrl():string {
return this._serverUrl;
}
set serverUrl(value:string) {
if (value.length > 0) {
if (value.charAt((value.length - 1)) == "/") {
value = value.substr(0, value.length - 1);
}
this._serverUrl = value;
}
}
public connect(url, opts?):void {
if (this._connected) {
this._socket.disconnect();
}
// Make URL optional
if ('object' === typeof url) {
opts = url;
url = null;
}
// this._url = url || null;
// this._opts = opts || {}
if (url) {
this.serverUrl = url;
} else if (this._opts.url) {
this.serverUrl = this._opts.url;
} else if( !(this._serverUrl.length > 0)) {
this._serverUrl = undefined;
}
this._opts.url = this._serverUrl;
// // If explicit connection url is specified, save it to options
// this._opts.url = url || this._opts.url || this._serverUrl;
this._socket = io.sails.connect(this._opts);
this._connected = true;
}
get(url, data?:any):Observable<any> {
let subject = new Subject();
this._socket.get(`${this._restPrefix}${url}`, data, (resData, jwres:IJWRes)=> {
if (io.sails.environment != "production") {
console.log("get::data", resData)
console.log("get:jwr", jwres)
}
if (jwres.statusCode < 200 || jwres.statusCode >= 400) {
subject.error(jwres.error)
} else {
subject.next(resData);
}
subject.complete();
})
return subject.asObservable();
}
post(url, data?:any):Observable<any> {
let subject = new Subject();
this._socket.post(url, data, (resData, jwres:IJWRes)=> {
if (io.sails.environment != "production") {
console.log("post::data", resData);
console.log("post:jwr", jwres);
}
if (jwres.statusCode < 200 || jwres.statusCode >= 400) {
subject.error(jwres.error)
} else {
subject.next(resData);
}
subject.complete();
})
return subject.asObservable();
}
put(url, data?:any):Observable<any> {
let subject = new Subject();
this._socket.put(url, data, (resData, jwres:IJWRes)=> {
if (io.sails.environment != "production") {
console.log("put::data", resData);
console.log("put:jwr", jwres);
}
if (jwres.statusCode < 200 || jwres.statusCode >= 400) {
subject.error(jwres.error)
} else {
subject.next(resData);
}
subject.complete();
})
return subject.asObservable();
}
delete(url, data?:any):Observable<any> {
let subject = new Subject();
this._socket.delete(url, data, (resData, jwres:IJWRes)=> {
if (io.sails.environment != "production") {
console.log("delete::data", resData);
console.log("delete:jwr", jwres);
}
if (jwres.statusCode < 200 || jwres.statusCode >= 400) {
subject.error(jwres.error)
} else {
subject.next(resData);
}
subject.complete();
})
return subject.asObservable();
}
on(eventIdentity:string):Observable<any> {
if (!this._pubsubSubscriptions[eventIdentity] || this._pubsubSubscriptions[eventIdentity].isComplete) {
this._pubsubSubscriptions[eventIdentity] = new Subject();
this._socket.on(eventIdentity, msg => {
if (io.sails.environment != "production") {
console.log(`on::${eventIdentity}`, msg);
}
this._pubsubSubscriptions[eventIdentity].next(msg);
})
}
return this._pubsubSubscriptions[eventIdentity].asObservable();
}
// public off(eventIdentity:string) {
//
// if(<Subject>this._pubsubSubscriptions[eventIdentity]) {
//
// }
//
// if (!<Subject>this._pubsubSubscriptions[eventIdentity].isComplete) {
// <Subject>this._pubsubSubscriptions[eventIdentity].complete();
// }
//
//
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment