Angular 2 observable doesn't 'map' to model - angularjs

As I'm learning Angular 2 I used an observable to fetch some data via an API. Like this:
getPosts() {
return this.http.get(this._postsUrl)
.map(res => <Post[]>res.json())
.catch(this.handleError);
}
My post model looks is this:
export class Post {
constructor(
public title: string,
public content: string,
public img: string = 'test') {
}
The problem I'm facing is that the map operator doesn't do anything with the Post model. For example, I tried setting a default value for the img value but in the view post.img displays nothing. I even changed Post[] with an other model (Message[]) and the behaviour doesn't change. Can anybody explain this behaviour?

I had a similar issue when I wanted to use a computed property in a template.
I found a good solution in this article:
http://chariotsolutions.com/blog/post/angular-2-beta-0-somnambulant-inauguration-lands-small-app-rxjs-typescript/
You create a static method on your model that takes an array of objects and then call that method from the mapping function. In the static method you can then either call the constructor you've already defined or use a copy constructor:
Mapping Method
getPosts() {
return this.http.get(this._postsUrl)
.map(res => Post.fromJSONArray(res.json()))
.catch(this.handleError);
}
Existing Constructor
export class Post {
// Existing constructor.
constructor(public title:string, public content:string, public img:string = 'test') {}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj['title'], obj['content'], obj['img']));
}
}
Copy Constructor
export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Object) {
this.title = obj['title'];
this.content = obj['content'];
this.img = obj['img'] || 'test';
}
// New static method.
static fromJSONArray(array: Array<Object>): Post[] {
return array.map(obj => new Post(obj);
}
}
If you're using an editor that supports code completion, you can change the type of the obj and array parameters to Post:
export class Post {
title:string;
content:string;
img:string;
// Copy constructor.
constructor(obj: Post) {
this.title = obj.title;
this.content = obj.content;
this.img = obj.img || 'test';
}
// New static method.
static fromJSONArray(array: Array<Post>): Post[] {
return array.map(obj => new Post(obj);
}
}

You can use the as keyword to de-serialize the JSON to your object.
The Angular2 docs have a tutorial that walks you through this. However in short...
Model:
export class Hero {
id: number;
name: string;
}
Service:
...
import { Hero } from './hero';
...
get(): Observable<Hero> {
return this.http
.get('/myhero.json')
.map((r: Response) => r.json() as Hero);
}
Component:
get(id: string) {
this.myService.get()
.subscribe(
hero => {
console.log(hero);
},
error => console.log(error)
);
}

Related

ERROR TypeError: Cannot read property 'details' of undefined

I have a plain text on local server that i want to display on my web page using angular. I have my model, service and component.
So I am getting an error at this line >> this.paragraphs = this.announcement.details.split('#');
I tried using ? operator (this.paragraphs = this.announcement?.details.split('#')) but it could not build.
MODEL
export class Announcements
{
public id: number;
public details: string;
public date: Date;
}
SERVICE
getAnnouncementById(id)
{
return this.http.get<Announcements>('http://localhost:49674/api/Announcements/' + id)
.pipe(catchError(this.errorHandler));
}
COMPONENT-.ts
import { Announcements } from '../models/Announcement';
export class ReadMoreComponent implements OnInit
{
public announcementId;
public announcement : Announcements
public paragraphs = [];
constructor(
private route: ActivatedRoute,
private router:Router,
private announcementservice: AnnouncementsService
){}
ngOnInit()
{
this.route.paramMap.subscribe((params:ParamMap) => {
let id = parseInt(params.get('id'));
this.announcementId = id;
this.getAnnouncenentById(id)
//split
this.paragraphs = this.announcement.details.split('#');
})
}
getAnnouncenentById(id){
this.announcementservice.getAnnouncementById(id)
.subscribe(data => this.announcement = data);
}
COMPONENT-.html
<div class="article column full">
<div *ngFor=" let paragraph of paragraphs">
<p>{{paragraph.details}}</p>
</div>
</div>
this.paragraphs = this.announcement.details.split('#'); is called before this.announcement = data so this.annoucement is undefined in that moment.
To be sure that both values already comes form observables you can use combineLatest function or switchMap operator.
Adding ? operator is workaround. Your observable still can call with unexpected order.
e.g.:
this.route.paramMap.pipe(switchMap((params: ParamMap) => {
let id = parseInt(params.get('id'));
this.announcementId = id;
this.getAnnouncenentById(id);
return this.announcementservice.getAnnouncementById(id)
})).subscribe((data) => {
this.announcement = data
this.paragraphs = this.announcement.details.split('#');
});
In that code subscription will start after first observable emits value.

Constructor of class 'Blob' is private and only accessible within the class declaration

import { Blob } from '#firebase/firestore-types';
#Injectable()
export class ImagehandlerProvider {
nativepath: any;
firestore = firebase.storage();
imagestore: any;
constructor(public filechooser: FileChooser, public blob: Blob) {
console.log('Hello ImagehandlerProvider Provider');
}
uploadimage() {
var promise = new Promise((resolve, reject)=> {
this.filechooser.open().then((url)=> {
(<any>window).FilePath.resolveNativePath(url, (result)=> {
this.nativepath = result;
(<any>window).resolveLocalFileSystemURL(this.nativepath, (res)=> {
res.File((resFile)=> {
var reader = new FileReader();
reader.readAsArrayBuffer(resFile);
reader.onloadend = (ent: any) => {
// var imgBlob = new Blob([ent.target.result], {type: 'image/jpeg'});
var imgBlob = new Blob([ent.target.result], {type: 'image/jpeg'});
var imgStore = this.firestore.ref(firebase.auth().currentUser.uid).child('profilepic');
imgStore.put(imgBlob).then((res)=> {
alert('Upload successful');
}).catch((error)=> {
alert('Upload failed' + error);
})
}
})
})
})
})
})
}
}
The code above has a simple problem. I am on the 3rd day learning ionic-angular, I want to implement image upload, and I think by default angular makes all imported classes private. I have searched online how to Blob is implemented and have sen that it is by instantiating the Blob class, which I did, since the class is made private by default it's not accessible so I have to create a public property in the constructor of this class. In short way, without creating this property I am getting this error:
[ts] Constructor of class 'Blob' is private and only accessible within the class declaration.
How do I make use of the Blob class

ngShow expression is evaluated too early

I have a angular component and controller that look like this:
export class MyController{
static $inject = [MyService.serviceId];
public elements: Array<string>;
public errorReceived : boolean;
private elementsService: MyService;
constructor(private $elementsService: MyService) {
this.errorReceived = false;
this.elementsService= $elementsService;
}
public $onInit = () => {
this.elements = this.getElements();
console.log("tiles: " + this.elements);
}
private getElements(): Array<string> {
let result: Array<string> = [];
this.elementsService.getElements().then((response) => {
result = response.data;
console.log(result);
}).catch(() => {
this.errorReceived = true;
});
console.log(result);
return result;
}
}
export class MyComponent implements ng.IComponentOptions {
static componentId = 'myId';
controller = MyController;
controllerAs = 'vm';
templateUrl = $partial => $partial.getPath('site.html');
}
MyService implementation looks like this:
export class MyService {
static serviceId = 'myService';
private http: ng.IHttpService;
constructor(private $http: ng.IHttpService) {
this.http = $http;
}
public getElements(): ng.IPromise<{}> {
return this.http.get('./rest/elements');
}
}
The problem that I face is that the array elements contains an empty array after the call of onInit(). However, later, I see that data was received since the success function in getELements() is called and the elements are written to the console.
elements I used in my template to decide whether a specific element should be shown:
<div>
<elements ng-show="vm.elements.indexOf('A') != -1"></elements>
</div>
The problem now is that vm.elements first contains an empty array, and only later, the array is filled with the actual value. But then this expression in the template has already been evaluated. How can I change that?
Your current implementation doesn't make sense. You need to understand how promises and asynchronous constructs work in this language in order to achieve your goal. Fortunately this isn't too hard.
The problem with your current implementation is that your init method immediately returns an empty array. It doesn't return the result of the service call so the property in your controller is simply bound again to an empty array which is not what you want.
Consider the following instead:
export class MyController {
elements: string[] = [];
$onInit = () => {
this.getElements()
.then(elements => {
this.elements = elements;
});
};
getElements() {
return this.elementsService
.getElements()
.then(response => response.data)
.catch(() => {
this.errorReceived = true;
});
}
}
You can make this more readable by leveraging async/await
export class MyController {
elements: string[] = [];
$onInit = async () => {
this.elements = await this.getElements();
};
async getElements() {
try {
const {data} = await this.elementsService.getElements();
return data;
}
catch {
this.errorReceived = true;
}
}
}
Notice how the above enables the use of standard try/catch syntax. This is one of the many advantages of async/await.
One more thing worth noting is that your data services should unwrap the response, the data property, and return that so that your controller is not concerned with the semantics of the HTTP service.

Is it possible to run some code after an abstract extended method runs in typescript?

I have a typescript base class in my angular project called "Animal" that is extended for several types of animals. Here is some sample code to illustrate. Each extended class will implement it's own "getItems" method and then set "isItemsLoaded" after the promise resolves.
abstract class Animal {
items: Array<...> = [];
isItemsLoaded: boolean = false;
abstract getItems(): ng.IPromise<Array<...>>;
}
class Hippo extends Animal {
getItems() {
//return a promise to get a list of hippos
return this
.getHippos(...)
.then(list, => {
...
this.isItemsLoaded= true;
});
}
}
class Tiger extends Animal {
getItems() {
//return a promise to get a list of tigers
return this
.getTigers(...)
.then(list, => {
...
this.isItemsLoaded= true;
});
}
}
Can I somehow attach some code to run after the getItems resolves (like a finally method) in the Animal base class? I would like to be responsible for setting "isItemsLoaded" in the base. Is something like this possible?
abstract class Animal {
items: Array<...> = [];
isItemsLoaded: boolean = false;
abstract getItems(): ng.IPromise<Array<...>>.AfterResolved(this.isItemsLoaded = true;);
}
You can use template method pattern. Something like this:
// stripped down code for simplicity
abstract class Animal {
isItemsLoaded = false;
protected abstract getItemsForAnimal(): ng.IPromise<Array<...>>;
getItems() {
const items = this.getItemsForAnimal();
this.isItemsLoaded = true;
return items;
}
}
class Hippo extends Animal {
protected getItemsForAnimal() {
// return a promise to get a list of hippos
}
}

Can I create a TypeScript class within a function and refer to its parameters?

E.g. in angularJS I may use the following construction:
myApp.factory('MyFactory', function(injectable) {
return function(param) {
this.saySomething = function() {
alert("Param=" + param + " injectable=" +injectable);
}
};
});
This can later be used like this:
function(MyFactory) {
new MyFactory().saySomething();
}
When the function passed to the method factory gets invoked, the param injectable is caged and will further be available to new instances of MyFactory without any need to specify that parameter again.
Now I want to use TypeScript and obviously I want to specify that my MyFactory is newable, and has a function saySomething. How could I do this elegantly?
I could write something like this:
class MyFactory {
constructor(private injectable, private param) {}
saySomething() {
alert(...);
}
}
myApp.factory('myFactory', function(injectable) {
return function(param) {
return new MyFactory(injectable, param);
}
});
But this changes the API:
function(myFactory) {
myFactory().saySomething();
}
I wonder if it could be more elegant, because I like how the "new" expresses quite clearly that a new unique object is created and this object creation is the whole purpose of the factory.
** Edit: TypeScript >= 1.6 supports class expressions and you can now write things like:
myApp.factory(injectable: SomeService) {
class TodoItem {
...
}
}
** Original answer:
I have the same problem: with AngularJS and ES5, I enjoy dependency injection not polluting constructors and be able to use the new keyword.
With ES6 you can wrap a class inside a function, this is not yet supported by TypeScript (see https://github.com/Microsoft/TypeScript/issues/307).
Here what I do (MyFactory is now class TodoItem from a todo app to be more relevant):
class TodoItem {
title: string;
completed: boolean;
date: Date;
constructor(private injectable: SomeService) { }
doSomething() {
alert(this.injectable);
}
}
class TodoItemFactory() {
constructor(private injectable: SomeService) { }
create(): TodoItem {
return new TodoItem(this.injectable);
}
// JSON from the server
createFromJson(data: any): TodoItem {
var todoItem = new TodoItem(this.injectable);
todoItem.title = data.title;
todoItem.completed = data.completed;
todoItem.date = data.date;
return todoItem;
}
}
// In ES5: myApp.factory('TodoItem', function(injectable) { ... });
myApp.service('TodoItemFactory', TodoItemFactory);
class TodosCtrl {
// In ES5: myApp.controller('TodosCtrl', function(TodoItem) { ... });
constructor(private todoItemFactory: TodoItemFactory) { }
doSomething() {
// In ES5: var todoItem1 = new TodoItem();
var todoItem1 = this.todoItemFactory.create();
// In ES5: var todoItem2 = TodoItem.createFromJson(...)
var todoItem2 = this.todoItemFactory.createFromJson(
{title: "Meet with Alex", completed: false}
);
}
}
This is less elegant than with ES5 and functions (and not using classes with TypeScript is a no go) :-/
What I would like to write instead:
#Factory
#InjectServices(injectable: SomeService, ...)
class TodoItem {
title: string;
completed: boolean;
date: Date;
// No DI pollution
constructor() { }
saySomething() {
alert(this.injectable);
}
static createFromJson(data: string): TodoItem {
...
}
}
#Controller
#InjectFactories(TodoItem: TodoItem, ...)
class TodosCtrl {
constructor() { }
doSomething() {
var todoItem1 = new TodoItem();
var todoItem2 = TodoItem.createFromJson({title: "Meet with Alex"});
}
}
Or with functions:
myApp.factory(injectable: SomeService) {
class TodoItem {
title: string;
completed: boolean;
date: Date;
// No constructor pollution
constructor() { }
saySomething() {
alert(injectable);
}
static createFromJson(data: string): TodoItem {
...
}
}
}
myApp.controller(TodoItem: TodoItem) {
class TodosCtrl {
constructor() { }
doSomething() {
var todoItem1 = new TodoItem();
var todoItem2 = TodoItem.createFromJson({title: "Meet with Alex"});
}
}
}
I could write something like this
This is what I do
Can I create a TypeScript class within a function
No it needs to be at the top level of the file or in a module. Just FYI if were able to create it inside a function the information would be locked inside that function and at least the type info would be useless.
What's the reason for instantiating multiple instances of MyFactory? Would you not want a single instance of your factory to be injected into your dependent code?
I think using the class declaration you provided will actually look like this once injected:
function(myFactory) {
myFactory.saySomething();
}
If you are really needing to pass a constructor function into your dependent code, then I think you will have to ditch TypeScript classes, since they can't be defined inside of a function which means you would have no way to create a closure on a variable injected into such function.
You do always have the option of just using a function in TypeScript instead of a class. Still get the strong typing benefits and can call 'new' on it since it is still a .js function at the end of the day. Here's a slightly more TypeScriptiffied version:
myApp.factory('MyFactory', (injectable: ng.SomeService) => {
return (param: string) => {
return {
saySomething: () {
alert("Param=" + param + " injectable=" +injectable);
}
};
};
});

Resources