Blog Archives

May 8th, 2017
3:55 pm
How to refer to child component instances from an Angular component class

Posted under Angular
Tags ,

With Angular, the component objects are automatically created and associated with their corresponding elements in the template.

This raises the question then – if you want to refer to a child object from a parent component, how do you do it? There may be multiple child components of the same time in the parent component, so how do you get a reference to a specific one?

As a contrast, when using JSF for example to refer to child component code, the parent managed bean (= component object in Angular) is actually responsible for declaring the managed bean objects for its children. On the page, the child component element will typically have a specific e.g. controller attribute where the managed bean for that child is passed in, e.g. as <child controller=#{controller.child}>…  where controller.child  refers to the child property of the parent managed bean. In this way, unlike Angular, the object hierarchy is explicitly declared in the code.

In Angular, there are a number  of ways to do this, but in the end they all come down to using reference information from a particular template element to direct which object is required.

It is instructive to read the whole section on Angular template syntax in the Angular docs, which includes all the binding techniques.

1/ Passing an element reference in a method call from the template

<ion-auto-complete id="location-search" #locationSearch [dataProvider]="locationsAutoCompleteService"
(itemSelected)="onItemClicked($event, locationSearch)"></ion-auto-complete>

In this case, (itemSelected)="onItemClicked($event, locationSearch)" is passing the element reference #locationSearch as the second argument to onItemClicked. This passes the reference to the component object for  <ion-auto-complete>. (Note that in this case the first argument, $event, is the actual location object that was clicked in an autocomplete list).

2/ Using the @ViewChild decorator in the parent class, passing it a child reference used in the template

export class AutoCompleteComponent {

@Input() public dataProvider: any;
@Output() public itemSelected: EventEmitter<any>;
@ViewChild(Searchbar) searchBar: Searchbar;

In this case, the component only contains a single searchbar, so using a class reference is not ambiguous. If there were multiples, the first one would be taken. You can inject references to multiple children via @ViewChildren if there is more than one present – this gives you access to an array of them.

Where you want to use a reference to a specific element, you can use @ViewChild with an element reference, e.g. in 1/ above you would use  #locationSearch to inject a referent to the <ion-auto-complete #locationSearch > element as follows:-

@ViewChild(‘#locationSearch’) searchBar: Searchbar;

3/ Another related technique is to make a method call in the template e.g. in an event call, using an element reference to another element in the component. This is detailed here. Note that <child-component #f contains the #f element reference, and the inc() method on the #f element is called from the button click event using <button (click)=”f.inc()”>

@Component({
    selector: 'child-component',
    inputs: ['bar'],
    template: `"{{ bar }}" in child, counter  {{ n }}`
})
class ChildComponent{
    constructor () {
        this.n = 0;
    }
    inc () {
        this.n++;
    }
}

@Component({
    selector: 'my-app',
    template: `
        <child-component #f [bar]="bar"></child-component><br>
        <button (click)="f.inc()">call child func</button>
        <button (click)="bar = 'different'">change parent var</button>
    `,
    directives: [ChildComponent]
})
class AppComponent {
    constructor () {
        this.bar = 'parent var';
    }
}

bootstrap(AppComponent);  

There is a working plunker for the above example here.

No Comments »

May 8th, 2017
12:36 pm
Angular 2 -Difference between @Input and inputs in Angular2 Components?

Posted under Angular
Tags ,

This post discusses the alternative way of specifying input parameters for angular 2.

This can be done using either:-

@Component{(
    selector: "my-component",
    inputs: ["attr"]
)}
export class MyComponent {
}

or alternatively:-

@Component{(
    selector: "my-component"
)}
export class MyComponent {
    @Input()
    public attr: any;
}

No Comments »

April 27th, 2017
4:15 pm
Angular 2 – Reactive Programming/Observables with multiple HTTP API calls

Posted under Angular
Tags , ,

A common pattern used in service layers is to make calls to an underlying repository or API, and then map the results to domain layer objects via mappers/convertors. Often, it may be necessary to make multiple repository calls and then combine them in the mapping phase to create the resulting domain object graph which is then returned. With traditional synchronous calls, e.g. to an underlying JPA repository, this is a straightforward exercise.

However, Angular 2 by default makes HTTP api call results available asynchronously as Observables, which poses an immediate issue with how to combine the results. I certainly did not want to embed Observables as properties within my domain objects, as I wanted the domain objects as POTOs (Plain Old Typescript Objects) and did not want to couple them/pollute them with Observables.

Handling the above pattern is in fact straightforward, but does involve a paradigm shift compared with imperative OO style programming as you need to get your head around reactive programming, in this case ReactiveX/RxJS which Angular uses.

  • In this case we are using RxJs Observables for which the api is documented here.
  • The available operators for use with Observables are documented here.
  • ReactiveX/RxJs makes extensive use of Marble diagrams an example of which may be found here.
  • Another useful introduction site to RxJS may be found here.

Note that it is possible to convert the observables to promises and use promise chaining to achieve similar results. However, I decided to stick with observables as the majority of comments online such as this post indicate that observables can do all that promises can, and more, and they are the default/chosen direction for Angular 2. It felt counter intuitive to have to convert the observables to promises all the time when there was no real need – whilst  and to do so appeared to go against the chosen way forward for Angular 2.

My first prototype needed to combine 2 API calls, and for this I used the combineLatest instance method. (This is called on one Observable and allows one or more other observables to be combined with it. There is also a static method available on the Observable class.) I found this solution in this StackOverflow post. These methods do do the following :-

  1. Combine 2 or more observables and emits a single output observable
  2. Before the output observable emits an item, all of the input observables must have emitted at least one item
  3. Once all the observables have emitted something, the output emits an output item.
  4. It continues to emit items whenever any of the input observables emit another item.
  5. Note that in our case, multiple emits for an observable do not occur. Whilst we are using observables, each one will only emit a single output item in our case, when the HTTP call completes.
  6. Note that per the example code below, I use lambdas (=> operator) routinely. The lambda used on the return of combineLatest will be called when the output observable emits an item (i.e. when both the HTTP calls have completed). The other lambdas are just used for standard synchronous filter/map/reduce operations on the arrays – these are standard in Javascript and hence Typescript, so they are not asynchronous/using observables.

For the requirement of my original pattern, i.e. make a number of repository calls, then map them all to a domain object graph, the above approach works fine. Note that there are a number of other operators on observables which are quite nuanced and this example just scratches the surface of Reactive programming, but in my experience the above is a very common pattern. Some of the other operators/methods distinguish between emits on an observable and the observable actually closing. As in the above case we just get one emit from each, we don’t need to get into that issue.

An outline example from my prototype code follows (imports and domain objects omitted for clarity). Note that it is just a prototype and a number of issues have not been properly addressed yet (such as externalisation of configuration data such as API urls):-

places-service.ts

@Injectable()
export class PlacesService {

static apiBase: string = 'http://localhost:5984/places-guide/';
static apiGetByLocationName: string = `${PlacesService.apiBase}_design/places/_view/placesByLocationName?include_docs=true`;
static apiGetFeatures: string = `${PlacesService.apiBase}_design/places/_view/featuresByOrdinal?include_docs=true`;

constructor(private http: Http, private featureMapper: FeatureMapper, private placeMapper: PlaceMapper) {}

fetch(): Observable<Place[]> {
return this.http.get(PlacesService.apiGetByLocationName)
 
       //The lambda here is called when the output observable emits an item (which only happens once when both HTTP calls complete).
.combineLatest(this.http.get(PlacesService.apiGetFeatures), (placesRows, featuresRows) => {
let features: Feature[] = this.featureMapper.mapAll(featuresRows.json().rows);
let places: Place[] = this.placeMapper.mapAll(placesRows.json().rows, features, PlacesService.apiBase);
return places;
});
}
}
 
place-mapper.ts
@Injectable()
export class PlaceMapper {

constructor(private placeFeaturesMapper: PlaceFeaturesMapper) {};

public map(row: any, placeFeatures: PlaceFeatures, apiBase: string): Place {
let place: Place = Place.create(
row.id,
row.doc.name,
row.doc.strapline,
row.doc.description,
Address.create(
row.doc.address.address1,
row.doc.address.locality,
row.doc.address.postTown,
row.doc.address.postCode),
row.doc.lat,
row.doc.long,
row.doc.website,
row.doc.phone,
row.doc.email,
placeFeatures,
apiBase + row.doc._id + "/thumbnail.jpg",
apiBase + row.doc._id + "/detail.jpg"
);
return place;
}

public mapAll(rows: any[], features: Feature[], apiBase: string){
let placesPlaceFeaturesMap: {[key: string]: PlaceFeatures } = this.createPlacesPlaceFeaturesMap(rows, features);
return rows
 
      //this is standard array filtering and mapping with lambdas
.filter(row => row.doc.type == 'place')
.map(row => this.map(row, placesPlaceFeaturesMap[row.doc.placeFeaturesId], apiBase));
}

createPlacesPlaceFeaturesMap(rows: any[], features: Feature[]): {[key: string]: PlaceFeatures } {
let placesPlaceFeaturesMap: {[key: string]: PlaceFeatures } =
rows.filter(row => row.doc.type == 'placeFeatures')
        //This is a standard array lambda. Reduce is used as we are populating a single return object.
        .reduce((map, row) => {
map[row.doc._id] = this.placeFeaturesMapper.map(row, features);
return map;
 
        //Note that the {} is the seed/initial value for the reduce, where we initialise the empty output object
}, {}
      );
return placesPlaceFeaturesMap;
}
}
place-features-mapper.ts
 
@Injectable()
export cl

ass PlaceFeaturesMapper {

public map(row: any, features: Feature[]): PlaceFeatures {
let list: PlaceFeature[] = this.buildList(row.doc._id, row.doc.placeFeatures, features );
let map: {[key: string]: PlaceFeature} = this.buildMap(list);
return PlaceFeatures.create(row.doc._id, list, map, features);
}

buildList(placeFeaturesId: string,
rawPlaceFeatures: {[key: string]: {rating: number} },
features: Feature[]): PlaceFeature[] {
let placeFeatures: PlaceFeature[] = features
.filter(feature => rawPlaceFeatures[feature.id])
.map(feature => PlaceFeature.create(
placeFeaturesId,
feature.id,
feature.ordinal,
feature.name,
feature.description,
feature.searchable,
feature.rateable,
rawPlaceFeatures[feature.id].rating)
);
return placeFeatures;
}

buildMap(placeFeatures: PlaceFeature[]): {[key: string]: PlaceFeature} {
let placeFeaturesMap: {[key: string]: PlaceFeature} =
placeFeatures.reduce((map, placeFeature) => {
map[placeFeature.featureId] = placeFeature;
return map;
}, {});
return placeFeaturesMap;
}
}

 
feature-mapper.ts
@Injectable()
export class FeatureMapper extends AbstractMapper<any, Feature> {

public map(row: any): Feature {
let feature: Feature = Feature.create(
row.id,
row.doc.ordinal,
row.doc.name,
row.doc.description,
row.doc.searchable,
row.doc.rateable);
return feature;
}
}
 
abstract-mapper.ts
export abstract class AbstractMapper<R,T> {
public abstract map(row: R): T;

public mapAll(rows: R[]): T[] {
return rows.map(row => { return this.map(row);});
}
}
 

No Comments »

April 26th, 2017
8:21 am
Ionic 2 Super Starter template application – Cannot find module "ionic-native"

Posted under Ionic
Tags , ,

This template is noteworthy as it contains a number of simple ready made use cases/patterns such as swipe gesture support, master/detail pages, searching, and simple entry forms.
As per this post, a tutorial starter app with the above template should be created as follows:-

ionic start my-super-starter-app super –v2
npm install

When I tried to run this I got the following error trace:-

Runtime Error

Cannot find module "ionic-native"

Stack

Error: Cannot find module "ionic-native"
at g (http://localhost:8100/build/polyfills.js:3:7133)
at Object.<anonymous> (http://localhost:8100/build/main.js:108352:7)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at Object.<anonymous> (http://localhost:8100/build/main.js:82204:73)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at Object.<anonymous> (http://localhost:8100/build/main.js:120594:70)
at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
at http://localhost:8100/build/main.js:66:18 at http://localhost:8100/build/main.js:69:10

Ionic Framework: 3.0.1
Ionic Native: ^3.5.0
Ionic App Scripts: 1.3.0
Angular Core: 4.0.0
Angular Compiler CLI: 4.0.0
Node: 7.5.0
OS Platform: Windows 7
Navigator Platform: Win3
User Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36

This Ionic forum post documents the problem, which appears to be because the starter template expects A version of ionic-native lower than 3 (mine was 3.5.0 as above). As per the post, I tried the following:-

  1. Edited my package.json and changed the ionic-native version to 2.9.0
  2. Entered npm install ionic-native –save

This did not work, it failed with a similar error.

Fortunately the post links to an updated template as the solution, in github here.

This can be cloned and used instead of entering ionic start my-super-starter-app super –v2

I tried the fixed version and it worked correctly. Note ref the comments in the various posts that it was not necessary to install ionic-native explicitly via npm install ionic-native –save

No Comments »

March 10th, 2017
11:02 am
Styling and Theming an Ionic Application

Posted under Ionic
Tags , , ,

This isn’t obvious when you browse the documentation, at least when starting out.

I’m coming from having used for example ThemeRoller with PrimeFaces, where structural css is defined by the components, to give size, shape, layout etc. Theming css   is defined by the theme, using common style classes etc. used by all components, to give colours, textures and fonts etc. The two concepts are mutually orthogonal, so you can use any theme with any component, and create your own theme.

I’ve seen theming and themes mentioned on a number of Angular/Ionic related sites, but without the same concept of orthogonality – themes are mentioned along with specialised components which are deemed to be part of a theme. Therefore, theming in Angular appears to encompass more than just the look and styling of components, but also the actual components and their functionality.

This could be summarised simply as follows:- ThemeRoller encompasses the look of an application, with components such as Primefaces encompassing the feel of the application.

With Angular/Ionic, the concept of theming is broader and appears to encompass both look and feel.

 

Some excellent posts by Josh Morony on how to theme an ionic application help to get under the hood on all this, and are available here:-

https://www.joshmorony.com/a-guide-to-styling-an-ionic-2-application/

https://www.joshmorony.com/a-list-of-common-css-utility-attributes-in-ionic-2/

https://www.joshmorony.com/tips-tricks-for-styling-ionic-2-applications/

https://www.joshmorony.com/hacking-css-in-ionic-2/

No Comments »

March 10th, 2017
10:26 am
Navigation Techniques in Ionic vs Angular2

Posted under Ionic
Tags , , ,

Whilst Angular 2 routing is handled via routers, Ionic takes a different approach with the use of the NavController and related components based on it like Nav and Tab.

Ionic navigation allows views to be pushed and popped from a navigation stack, and allows a root page to be established for a particular navigation stack.

A useful tutorial on Ionic Navigation may be found here.

No Comments »

May 15th, 2012
7:22 pm
Oracle XE 11g R2 installation issue on Windows 7 64 bit

Posted under Oracle
Tags , , ,

During installation, I received the following error message:-

“The installer is unable to instantiate the file …{…}\KEY_XE.REG”

The installation was mostly correct but I was unable to access the getting started/home page.

This post here details a workaround for the issue but this did not  work for me.

In the end, I recreated the Get_Started.url file under (in my case) E:\oraclexe\app\oracle\product\11.2.0\server.

This contained a parameter placeholder for the HTTP port, and I just edited the correct port in directly. Note that for some reason it was not possible to change the existing shortcut. I had to delete it and create a new one of the same name, which then worked fine.

Whilst doing this, I also changed the HTTP port that the web interface listens on. This is done by running a stored procedure, and is detailed in both this post and also this alternative post. Both posts detail the same method.

Note also for XE 11g R2 that the getting started page (which corresponds to the old 10g home page) no longer has the means to create schemas or to run sql queries. Schemas/users can be created via SQLplus, or via TOAD or SQLDeveloper.

Note that TOAD 8 is not compatible with 11g. The latest free TOAD now lasts for a year and is excellent with plenty of functionality, albeit with an occasional nag/advert for the paid version. The paid version is around $800 for a seat which is very high for a SQL development tool, even if it is a good one. Note that the free TOAD is available from Toad World here, but is not available from the main Quest Software site – this appears to be a marketing decision to keep the free version out of sight from people who may be persuaded to part with money for the paid one. I should not complain too much as they are after all providing an excellent free tool.

No Comments »

May 15th, 2012
6:58 pm
Automatically disabling Sleep during Acronis True Image Home Backups

Posted under Windows 7
Tags , , ,

Previously this had been an issue as the PC would sleep during the validation of a Backup, so I manually switched to an Always On power plan.

With the current PC build I was using, the PC would hang and not shut down cleanly if it was put into sleep and woken whilst an eSATA drive was attached to the 2-port STARTECH card I was using. Providing the PC did not sleep, all was fine.

I therefore looked for a means of automatically switching to always on for Backup runs. Rather than switch back to the normal power plan automatically after the backup, I elected to leave Always On set and switch back to normal on every startup. This way, I would be sure that if I still had the eSATA drive connected after a backup, the pc would not sleep.

This Acronis forum post which refers to this instructional pdf detail a workaround to the problem, which involves coding a batch file to switch power plans, and calling it as a pre/post custom command in Acronis in the backup settings.

In addition, as I wanted to set the plan back to normal at boot time, I used the technique from this StackOverflow post which worked correctly. Originally I had tried using a scheduled task triggered at boot time, but it refused to run and did not give a reason why.

My registry settings file, batch files, and vbs script are listed below for reference. Note that the GUIDS correspond to the particular power plans, and are unique for each one and different for each pc – see the above pdf for details of how to list the power plans with their corresponding GUIDs.

This fixed the problem, but I remain unimpressed that Acronis does not handle this automatically or have a setting for it in a backup definition. You can tell it to prevent sleep for scheduled backup runs, but not for manually initiated ones.

 

SetPowerPlanNormal.reg

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"SetPowerPlanNormal"="wscript.exe \"C:\\System Management\\RunInvisibleBatchFile.vbs\" \"C:\\System Management\\SetPowerPlanNormal.bat\""

RunInvisibleBatchFile.vbs

CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False

SetPowerPlanNormal.bat

:: Change Power Plan to Normal.
::
@ECHO OFF
POWERCFG -SETACTIVE ccaec46d-cbf8-42af-9e8f-ab66182942f7
::
@EXIT

SetPowerPlanAlwaysOn.bat

:: Change Power Plan to AlwaysOn.
::
@ECHO OFF
POWERCFG -SETACTIVE 499ab33e-0735-4605-8ccc-98211478164b
::
@EXIT

No Comments »

February 27th, 2012
9:32 am
Passing the “this” reference for a subclass from a self-referential generic superclass

Posted under Java
Tags , , ,

Update 7/12/22

Previously I have implemented a composite iterator for iterating a tree of tags from a search on a PropertyTree implementation. Note that in this case, the abstract base class for the composites was a TagTree, and the concrete subclasses were a TagList and a Tag. As a Tag did not need a list, the list of children was in the concrete TagList and not the TagTree. Therefore, the TagTree did not need to have generic references to self referential subtypes in the way the example below does – in fact it did not need to be generic at all. Therefore it did not suffer this problem. For further clarity see the example below from Angelika Langer here. In her code, the list is in the abstract superclass which is why it suffers the problem below and potentially needs the infamous getThis trick per below.

Original Post

Some generic classes are recursively self-referential, such as in the following abstract class statement for a tree node :-

public abstract class Node <N extends Node<N>>  {

}

In this situation it is sometimes necessary for example to pass a reference to this from the superclass to a specific subclass which expects an argument of type N :-

public void methodA(N node) {
//do something with the passed node
}

public void methodB(N node) {
node.methodA(this); // error – incompatible types
}

In the above fragment, the error is because this in the superclass has a type of Node<N> which does not match N.

Another related use case is where a fluent API returns a ‘this’ reference from each of the fluent methods. If for example a fluent method in an abstract base class needs to return a ‘this’, as above the reference needs to be for the concrete subclass so the same problem occurs.

The topic is discussed in detail in Java Generics and Collections, section 9.4 on the Strategy pattern. The section from the book may be viewed online at Flylib here.

Angelika Langer also discusses it in more detail her Generics FAQ here

In the above case, the problem can be solved with the so-called getThis trick. An abstract getThis method is defined in the superclass, and implemented in each subclass:-

Superclass

protected abstract N getThis();

Subclass

protected Subtype getThis() {return this}; // where Subtype is the concrete subtype of N

Now the superclass can obtain a type correct reference to this and pass it without error:-

public void methodB(N node) {
node.methodA(getThis()); // this time it works
}

As Angelika Langer points out in her examples, there can be other ways around this kind of problem depending on the situation, but sometimes you do need the getThis trick.

No Comments »

February 9th, 2012
12:01 pm
EJB methods–returning status codes vs throwing exceptions

Posted under EJB
Tags , , ,

Exceptions are hotly debated on line, as is this issue as to whether to return status or throw an exception. There is no straight answer for all cases, but for the projects I am working on, I am adopting the following.

  1. Many EJB methods return data as lists of entities for example, and to return a status code as well is a nuisance as you need to build a wrapper class for this.
  2. My present way forward therefore is to throw exceptions in the EJB methods, for example when you attempt to delete a non existent row.
  3. Even though some methods like delete have no return and could return a status, others do return data and could not easily do it this way. I prefer to be consistent in my approach.
  4. Therefore, I will throw checked exceptions for these ‘important’ ones like non existant data, that the caller should check for.
  5. If I am using  a command pattern as per my post on this here, I will then catch these in the command objects,  and convert to one of the status enum values I have proposed for my Command Pattern implementation. This is an ideal place to do it, exceptions are not friendly to the command pattern mechanism if you want to continue from one, and I have already added the generic status enum idea.
  6. For cases when I do not use command patterns, a similar approach could be used by catching the exceptions in the model layer and converting to a status enum there. My model layer is stateful, and typically my fetch methods in the model populate result properties and then return void. These would be ideally placed to catch any exceptions from the service layer and return a status enum instead (or just return the enum status from a command if that was used).
  7. Coupling and isolation of the status enum needs to be considered. Where the enum is defined in the model, the view/controller layer has no dependency on the service layer. However, if the enum were to be defined in the service layer, the view then has a dependency on it as it uses that enum. This is (perhaps to a lesser extent) also true if the enum is defined in a command class, as these are also service layer classes. I may therefore decide to map them to a model specific enum (which may be similar).

No Comments »