How to write angular filter definition in controller with typescript - angularjs

I have following working code, its just that i am using javascript, want to convert it into full typescript code.
My html has div with ng-repeat with a filter definition, the definition is available on scope, as follows
<input type="text" ng-model="vm.searchText"/>
<div ng-repeat="item in vm.items | filter:vm.filterItems(vm.searchText)">{{item.name}}</div>
and the view's controller class has scope vm properties searchText, items and a filterItems(filter definition) as follows
export interface IMyScope extends ng.IScope
{
vm: MyController;
}
export class ItemClass {
private _name: string;
constructor(name: string) {
this._name = name;
}
public get name(): string {
return this._name;
}
}
export class MyController
{
private _searchText: string;
private _items: ItemClass[];
constructor(scope: IMyScope) {
scope.vm = this;
this._items = [];
this._items.push(new ItemClass("test1"));
this._items.push(new ItemClass("value2"));
this._items.push(new ItemClass("foo"));
}
public get searchText(): string {
return this._searchText;
}
public set searchText(value: string) {
this._searchText = value;
}
public get items(): ItemClass[] {
return this._items;
}
public filterItems(criteriaText: string) {
return function (item: ItemClass): boolean {
if (!criteriaText) {
return true;
}
return item.name.toLowerCase().indexOf(criteriaText.toLowerCase()) > -1;
}
}
}
I want to convert this filterItems in typescript,
Thanks in Advance

its just that i am using javascript, want to convert it into full typescript code.
I want to convert this filterItems in typescript,
What you have is already TypeScript. You can tell by the use of type annotations.

Related

Angular ngfor doesnt render list

I am using NGFor in my Html Page with an array, but I get the following error.
landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngDoCheck (common.js:4355)
at checkAndUpdateDirectiveInline (core.js:33470)
at checkAndUpdateNodeInline (core.js:46564)
at checkAndUpdateNode (core.js:46503)
at debugCheckAndUpdateNode (core.js:47529)
at debugCheckDirectivesFn (core.js:47472)
at Object.updateDirectives (landingpage.component.html:142)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:47460)
at checkAndUpdateView (core.js:46468)
at callViewAction (core.js:46834)
My ngFor looks so:
<div class="flex-container wrap" *ngFor="let item of newestProducts">
<div class="card flex-item">
<img src="{{ item.pictureUrl }}" class="card-img-top"
alt="...">
<div class="card-body">
<p class="card-title">{{ item.aktPrice }}€</p>
<p class="card-text">{{ item.productname }}</p>
<a href="/details/{{item.id}}" class="btn btn-primary productbutton"><p class="productbuttontext">Zum
Produkt</p></a>
</div>
</div>
and my ts file looks so:
export class LandingpageComponent implements OnInit {
public images = [944, 1011, 984].map((n) => `https://mdbootstrap.com/img/Photos/Horizontal/City/4-col/img%20(60).jpg`);
public newestProducts: Product[];
public randomProduct: Product;
public gutscheine: Gutschein[];
public submitted = false;
constructor(private productService: ProductService, private gutscheinService: GutscheinService,
private router: Router, config: NgbCarouselConfig) { // customize default values of carousels used by this component tree
config.interval = 100;
config.wrap = false;
config.keyboard = false;
config.pauseOnHover = false;
}
public ngOnInit() {
this.newestProducts = [];
this.newestProducts = this.productService.getProductsNewest();
this.gutscheine = this.gutscheinService.getGutscheine();
this.randomProduct = this.productService.getProductsRandom();
}
public gotoList() {
this.router.navigate(['/landingpage']);
}
}
Can someone tell me, why I get this error and how to solve it ? If I use an ng-If I get the same error.
Here is my service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ProductService {
private baseUrl = 'http://localhost:8080/priceoffer24/api/product';
constructor(private http: HttpClient) { }
public getProductById(id: number): any {
return this.http.get(`${this.baseUrl}/products/${id}`);
}
public getProductByName(name: string): any {
return this.http.get(`${this.baseUrl}/products/${name}`);
}
public getProductsList(): any {
return this.http.get(`${this.baseUrl}/products`);
}
public getProductsNewest(): any {
return this.http.get(`${this.baseUrl}/products/newest`);
}
public getProductsRandom(): any {
return this.http.get(`${this.baseUrl}/products/random`);
}
public getProductsBySubcategorie(subcategorie: string): any {
return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}`);
}
public getProductsBySubcategorieId(id: number): any {
return this.http.get(`${this.baseUrl}/products/subcategorie/${id}`);
}
public getProductsByCategorie(categorie: string): any {
return this.http.get(`${this.baseUrl}/products/categorie/${categorie}`);
}
public getProductsByCategorieId(id: number): any {
return this.http.get(`${this.baseUrl}/products/categorie/${id}`);
}
public getProductsBySubcategorieAndCategorie(subcategorie: string, categorie: string): any {
return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}/categorie/${categorie}`);
}
}
and this is the dto:
import {Categorie} from './categorie';
import {Prices} from './prices';
export class Product {
public id: number;
public description: string;
public productname: string;
public link: string;
public pictureUrl: string;
public aktPrice: string;
}
The methods of the service returns any, and the component is casting it to an array.
Use 'async' pipe to subscribe and leave the TS file as is.
<div class="flex-container wrap" *ngFor="let item of newestProducts | async">
public getProductsNewest(): Observable<YourType> {
return this.http.get(`${this.baseUrl}/products/newest`);
}
public ngOnInit() {
this.newestProducts = [];
this.productService.getProductsNewest().subscribe(newest => {
this.newestProducts = newest
}, error=> console.log(error) ;
}

AngularJS Typescript Service Inject Error

I am trying to migrate AngularJS to typesript. I faced a weird issue of testController being undefined incase I define injections with static $inject like below.
Controller TS
class TestController {
private customerName : string;
private customerLink : string;
private contactDetails : any;
private userPosts : any;
static $inject = ["TestService", "CustomerContactService"];
constructor(private TestService: ITestService, private CustomerContactService: any) {
console.log("inside constructor TestController");
}
init(customerName, customerLink) {
if(customerName && customerLink) {
this.customerName = TestConstant.HELLO + customerName;
this.customerLink = customerLink;
}
}
getPosts() {
this.testService.getUserPosts().then((response : ng.IHttpPromiseCallbackArg<any>) =>{
this.userPosts = JSON.stringify(response.data);
});
}
getContactDetails() {
this.customerContactService.getContacts("sales").then((response : ng.IHttpPromiseCallbackArg<any>) =>{
this.contactDetails = JSON.stringify(response);
});
}
}
angular
.module("testModule")
.controller("testController", TestController);
Service TS
interface ITestService {
getUserPosts() : ng.IPromise<ng.IHttpPromiseCallbackArg<any>>;
}
class TestService implements ITestService {
static $inject = ['$http'];
constructor(private $http : ng.IHttpService) {
}
getUserPosts() : ng.IPromise<ng.IHttpPromiseCallbackArg<any>> {
return this.$http.get("https://jsonplaceholder.typicode.com/posts/1");
}
}
angular
.module("testModule")
.service("testService", TestService);
However, if I use in the following in my controller
static AngularDependencies = ["TestService", "CustomerContactService"];
OR
static helloWorld = ["TestService", "CustomerContactService"];
everything works fine. What am I doing wrong? and how do I use static $inject as that seems to be a convention?
Error:[ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=testController&p1=not%20a%20function%2C%20got%20undefined
TIA

AngularJS, TypeScript, Component Architecture [$injector:unpr] Unknown provider

I have the following issue and don't know how to resolve it.
Usually, I work in Angular 6 but get back for a while to AngularJS, and have some issues with DI I think.
I have the component architecture with typescript.
My appRootModule looks like this (w/o imports section)
export const appRootModule: IModule = module('testApp, ['asyncFilter'])
.component('appRoot', new AppRootComponent())
.component('postModal', new PostModalComponent())
.service('componentsDataService', ComponentDataService);
And that's the service that gives the error.
appRootController:
export class AppRootController implements IController
private $http: IHttpService;
private $cds: ComponentDataService;
constructor($http: IHttpService, $cds: ComponentDataService) {
this.$http = $http;
this.$cds = $cds;
/.../
}
public sendToModal(post: any): void {
this.$cds.sendModalData(post);
}
public $onInit = async (): Promise<void> => {};
}
And the service file:
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
export class ComponentDataService {
private modalSubject: Subject<any> = new Subject<any>();
public sendModalData(post: any): void {
/.../
}
public clearModalData(): void {
/.../
}
public getModalData(): Observable<any> {
return this.modalSubject.asObservable();
}
}
Please help. I'm about to cry.
it gives me :
[$injector:unpr] Unknown provider: $cdsProvider <- $cds
When TypeScript transpiles your code to javascript it strips out the types and you end up with something like
var AppRootController = (function() {
function AppRootController($http, $cds) { /.../ }
});
AngularJS can't find $cds and you get the error you're seeing. You need to use the name you have assigned to your service: componentsDataService. i.e.:
export class AppRootController implements IController
private $http: IHttpService;
private $cds: ComponentDataService;
constructor($http: IHttpService, componentsDataService: ComponentDataService) {
this.$http = $http;
this.$cds = componentsDataService;
/.../
}
public sendToModal(post: any): void {
this.$cds.sendModalData(post);
}
public $onInit = async (): Promise<void> => {};
}

Creating instance of class having $inject

I have created a class to open a modal dialog.
export class ModalDialog {
private open: boolean;
private modalInstanse: angular.ui.bootstrap.IModalServiceInstance;
constructor(
#Inject('$uibModal')
private $uibModal: angular.ui.bootstrap.IModalService
) {
this.open = false;
}
public isOpen(): boolean {
return this.open;
}
public closeDialog(): void {
this.modalInstanse.close();
}
public dismissDialog(): void {
this.modalInstanse.dismiss();
}
public openDialog( templateUrl: string, controller:any ): void {
this.modalInstanse = this.$uibModal.open({
templateUrl: templateUrl,
controller: controller
});
this.open = true;
this.modalInstanse.result.finally((): void => {
this.open = false;
});
}
}
Now how can I use this class.
I was expecting we can use it as
ModalDialog md = new ModalDialg();
md.openDialog(someTemplate,someController);
I am doing something wrong here. Can someone explain? Sorry if this seems like stupid question.
Do I need to pass $uibModal as parameter to ModalDialog() ?
Since $uibModal is injected what is the best way to create ModalDialog?

In Angular+Typescript can I inject services and provide parameter in constructor

If I have a service injection like this:
export class MyService {
private fooService: IFooService;
public static $inject = [ "fooService" ];
constructor(fooService: FooService) {
this.fooService = fooService;
}
}
But I would like to give fooService a parameter in its constructor, so can I?
If you want to calculate something or provide the parameter in the run/config phase use a Provider
class MyServiceProvider implements ng.IServiceProvider {
private customParameter;
public setCustomParameter(val) {
this.customParameter = val;
}
public $get():Function {
return () => {
return new MyService(this.customParameter);
};
}
}
You now can inject the MyServiceProvider in the config phase and call the setCustomParameter.
If you know what what the parameter is, you can use regular injection and just define an angular variable like this:
angular.constant(CONSTANT_NAME, 'CONSTANT_VALUE');
export class fooService {
public static $inject = [ "CONSTANT_NAME" ];
constructor(CONSTANT_NAME) {
}
}

Resources