Cannot find name 'headers'. in angular 2 - angularjs

enter image description here
I am working on angular 2.this is my ts file I called getRandomQuote() method in constructor.
But when i run the project i get below error:-
Cannot find name 'headers'. Did you mean the instance member 'this.headers'?
import {Component, ViewEncapsulation, Injectable} from '#angular/core';
import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
import { Http, Response, Headers,RequestOptions } from 'angular2/http';
import {BasicTablesService} from './basicTables.service';
import {BaCard} from '../../../../theme/components';
import {HoverTable} from './components/hoverTable';
import {BorderedTable} from './components/borderedTable';
import {CondensedTable} from './components/condensedTable';
import {StripedTable} from './components/stripedTable';
import {ContextualTable} from './components/contextualTable';
import {ResponsiveTable} from './components/responsiveTable';
import {AuthHttp, AuthConfig, AUTH_PROVIDERS } from 'angular2-jwt';
import {HTTP_BINDINGS} from 'angular2/http';
#Component({
selector: 'basic-tables',
viewProviders: [PaginationService],
pipes: [PaginatePipe, ResponsiveTable, ContextualTable],
encapsulation: ViewEncapsulation.None,
directives: [BaCard, HoverTable, BorderedTable, CondensedTable, StripedTable, ContextualTable, ResponsiveTable, PaginationControlsCmp,HTTP_BINDINGS],
styles: [require('./basicTables.scss')],
template: `
<todo-search></todo-search>
<table class="table table-hover">
<div >Enter ID: <input type="text" #listFilter (keyup)="0" style="color:black" /></div> <div>Alert on click<button (click)="clicked()" style="color:black">Click</button></div>
<span>{{ test }}</span>
<tr class="black-muted-bg">
<th class="align-left">ID</th>
<th class="align-left">Name</th>
<th class="align-left">Protocol</th>
<th class="align-left">Inbound Business Process</th>
<th class="align-left">Outbound Business Process</th>
</tr>
<tbody>
<tr *ngFor="let item of randomQuote | paginate: { itemsPerPage: 20, currentPage: p } | ResponsiveTable:listFilter.value ">
<td>{{item.connectionId}}</td>
<td>{{item.name}}</td>
<td>{{item.protocol}}</td>
<td>{{item.inBoundBPName}}</td>
<td>{{item.outBoundBPName}}</td>
</tr>
</tbody>
<pagination-controls (pageChange)="p = $event" #api></pagination-controls>
</table>
`,
providers: [BasicTablesService]
})
export class BasicTables {
public body = JSON.stringify(
{
"startIndex": 0,
"numofIds": 15,
"programId": null,
"emailId":"admin#justransform.com",
"searchStr":"",
"transactionId":"",
"status":"",
"srcConnectionName":"",
"destConnectionName":"",
"inBoundBPName":"",
"outBoundBPName":"",
"fileContent":""
}
);
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: headers });
private url = 'http://uat.justransform.com:8080/justransform/transaction/find?sortByColumn=transactionId&sortByOrder=Desc';
randomQuote:Array<any> = [];
getRandomQuote() {
this.http.post(this.url, this.body, this.options)
.map((res:Response) => res.json())
.subscribe(
data => {this.randomQuote = data},
err => this.logError(err),
() => console.log('Random Quote Complete')
);
}
logError(err) {
console.error('There was an error: ' + err);
}
clicked(event) {
alert("Alert");
}
constructor(public http: Http) {
this.getRandomQuote();
}
}

Your code defines the headers attribute in the class context and tries to access it directly after that using headers.
public headers = new Headers({ 'Content-Type': 'application/json' });
public options = new RequestOptions({ headers: headers });
The error message you get for that specifically tells you what to try:
Cannot find name 'headers'. Did you mean the instance member 'this.headers'?
This is because you defined headers in the class context. To properly access it, you have to use this.headers:
public options = new RequestOptions({ headers: this.headers });
// ^ here
See TypeScript Classes for more information.

Related

Angular 5 - JSON to "scope" binding to *NgFor

I want to bind the data that i get from my JSON request to the *NgFor to be able to read it out, This is how the data looks like that i get in:
{Id: null, Code: "9348892084", HasInfo: true, Info: Array(26)}
HasInfo:true
Info:
Array(26)
0:{ProductId: 32631, Name: "JNOOS", Image: "http://sd-m-mg", …}
1:{ProductId: 32969, Name: "SWIFT", Image: "http://sd-33087.jpg",…}
2:{ProductId: 32570, Name: "GABIX", Image: "http://sd-c7273.jpg", …}
3:{ProductId: 32473, Name: "MISMA", Image: "http://sd-mt8-8343e4d95.jpg", …}
I was working with AngularJS before and there i made the request as such:
$scope.getAll{
$http({
method: 'Get',
url: "http://URL/" + Code
})
.success(function (data) {
$scope.All = data.Info;
})
No i am moving to Angular5 and i would like to get the same array of information bind to the :
<div *ngFor="let x of info">
{{ x.Name }}
</div>
How would i adjust the below to get the same as above?
export class AppComponent {
readonly ROOT_URL = 'http://url/content/'
constructor(private http: HttpClient) {}
ngOnInit() {
this.getData()
}
getData() {
this.http.get(this.ROOT_URL + 'Getscope')
.subscribe(
data => {
var test = data;
// var info = data.Info = not valid!;
// var test can't be approached by *ngFor
console.log(test);
console.log(test.info);
//$scope.info = data.Info;
//this.info = data;
}, error => {
console.error("HTTP FAILURE ERROR!!!");
}
)
};
}
Also the json output has an array inside an object, do i say this correct?
From your code you are using info in html but not assigning to any class variable,
Take a public variable public info; and assign data using this.info = data.Info
Component:
export class AppComponent {
readonly ROOT_URL = 'http://url/content/'
public info;
constructor(private http: HttpClient) {}
ngOnInit() {
this.getData()
}
getData() {
this.http.get(this.ROOT_URL + 'Getscope')
.subscribe(
data => {
this.info = data['Info']; // here is the change
}, error => {
console.error("HTTP FAILURE ERROR!!!");
}
)
};
}
Your HTML can be same:
<div *ngFor="let x of info">
{{ x.Name }}
</div>
The simplest solution would be to use an async pipe. This way you do not need to subscribe to the stream returned by http.get.
app.component.ts
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
export class AppComponent {
readonly url = 'http://url/content/'
constructor(private http: HttpClient) {}
info$: Observable<any[]>;
ngOnInit() {
this.info$ = this.http.get(this.url + 'Getscope')
.pipe(map(resp => resp.Info));
}
}
app.component.html
<div *ngFor="let x of info$ | async">
{{ x.Name }}
</div>

Not able to display the value from Json response

I am trying to get a json web response from jersey web service using hibernate.The values are returned from database as i checked in the console.The problem is that when i try to print that in the angular like this
<h1>Welcome to Hibernate Jersey Angular CMS</h1>
<div id='err'></div>
<a href="add.html" class='btn btn-success'>New Article</a>
<p>
<div>
<table id='blogList' class="table table-bordered" ng-controller='MyController'>
<tr>
<th>Latest Articles</th>
<th>Actions</th>
</tr>
<tr ng-repeat='elem in data'>
<td>{{elem.id}}</td>
<td><a class='btn btn-warning' href="modify.html?id={{elem.id}}">Modify</a></td>
</tr>
</table>
</div>
</body>
<script src='javascripts/jquery2.1.3/jquery.min.js'></script>
<script src='javascripts/bootstrap3.3.2/js/bootstrap.min.js'></script>
<script src='javascripts/angular1.2.19/angular.js'></script>
<script src='javascripts/json/json2.js'></script>
<script>
function MyController($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
}
</script>
</html>
the value is not displayed.It is displayed blank like this
I know i am getting proper response as the number of rows min the image is same as the number of entries in the table.This is my code for hibernate
public List<Love> getAllLeaves() {
Session session = HibernateTest.getSession();
String hql = "from Love";
Query qry = session.createQuery(hql);
List<Love> list = qry.list();
Iterator i=list.iterator();
while(i.hasNext())
{
Love l=(Love) i.next();
//System.out.println("staretd");
}
session.close();
return list;
}
and the jersey code
#GET
#Path("list")
#Produces({ "application/json" })
public List<Love> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
Love m=(Love)i.next();
System.out.println(m.getLove());
}
return l;
}
and bean class
package com.king.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
public class Love {
public Love(String Love) {
this.id = Love;
}
public Love()
{}
public String getLove() {
return id;
}
public void setLove(String Love) {
this.id = Love;
}
#Id
#QueryParam("id")
private String id;
}
added network response

"Error in .People/Component class PeopleComponent - inline template:93:8 caused by: Error trying to diff '[object Object]'"

i am able to fetch data from the database which is showing in my network tab alright but my app gives an error when i am trying to display the fetched data in my table. The error display ""Error in .People/Component class PeopleComponent - inline template:93:8 caused by: Error trying to diff '[object Object]'""
//component
export class PeopleComponent {
People: Peoples[] = [];
constructor(private httpService: HttpService, private router: Router) {
this.httpService.getPeople()
.subscribe(data => {
this.People = data;
}
);
}
//service
getPeople() {
let headers = new Headers({ 'Authorization': 'Bearer ' + this.auth.token });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://example.com', options)
.map((response:Response) => response.json());
}
//table
<table class="table" id="table" >
<tr>
<th>#</th>
<th>Group</th>
<th>Country</th>
</tr>
<tbody>
<tr *ngFor="let people of People" >
<td>{{people.group}}</td>
<td>{{people.country}}</td>
</tr>
</tbody>
</table>
// updated table
<tbody>
<tr *ngFor="let key of People | keys; let i = index" >
<td>{{i + 1}}</td>
<td>{{People[key].first_name + " " + People[key].last_name}}</td>
<td>{{People[key].group}}</td>
<td>{{People[[key].country}}</td>
</tr>
</tbody>
//pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value) : any {
if(value) {
return Object.keys(value)
}
}
}
//image
*ngFor only supports iterating an array, not arbitrary classes.
You can use a pipe for example like the following to get an array of keys you can iterate:
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value) : any {
if(value) {
return Object.keys(value)
}
}
}
<tr *ngFor="let key of People | keys " >
<td>{{People[key].group}}</td>
<td>{{People[key].country}}</td>
</tr>
</tbody>

AngularJS Typescript Controller Values not updating page

I'm picking up Angular for the first time and coming from a .NET backround feel a lot more comfortable working with typescript.
I've got a problem where a cant seem to get values to update on a page when a controller populates the controller values with an object received from a service. I'm probably just making a noob error.
Can anyone give a pointer on what I'm doing wrong.
So my typescript is
module ConnectAdmin.Interfaces {
export interface ITemplate {
templateId: number;
name: string;
description: string;
}
}
module ConnectAdmin.Interfaces {
export interface ITemplateCollection {
total: number;
set: number;
skipped: number;
collection: Array<ITemplate>;
}
}
module ConnectAdmin.Controllers {
import TemplateCollection = Interfaces.ITemplateCollection;
export class TemplateIndexController {
static $inject = ["ConnectAdmin.Services.TemplateService"];
constructor(templateService: ConnectAdmin.Services.TemplateService) {
this.defaultTemplates = { skipped: 0, set: 0, total: 0, collection: [] };
this.templates = this.defaultTemplates;
this.processing = true;
this.store = this;
templateService.index(this.take, this.skip, this.successCallback, this.errorCallback);
this.processing = false;
}
successCallback(data: TemplateCollection) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] }
this.templates = data;
alert(this.templates.collection.length);
}
errorCallback(response: any) {
this.templates = this.defaultTemplates;
alert(response.status);
this.message = "An Error Occurred Contacting the API";
}
processing: boolean;
store = this;
defaultTemplates: TemplateCollection;
templates: TemplateCollection;
take = 20;
skip = 0;
message: string;
}
angular.module("ConnectAdmin").controller("ConnectAdmin.Controllers.TemplateIndexController", TemplateIndexController);
}
module ConnectAdmin.Services {
import TemplateCollection = Interfaces.ITemplateCollection;
import TemplateIndexController = Controllers.TemplateIndexController;
export class TemplateService {
constructor($http: ng.IHttpService) {
this.http = $http;
}
http: ng.IHttpService;
index(take: number, skip: number, successCallback: Function, errorCallback: Function) {
const req = {
method: "GET",
url: "https://localhost:44336/api/Templates?take=" + take + "&skip=" + skip,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
this.http(req).then(response => {
successCallback(response.data);
},
response => {
errorCallback(response);
});
//return { total: 1, skipped: 0, set: 1, collection: [{ templateId: 1, name: "Template 1", description: "" }] };
}
}
angular.module("ConnectAdmin").service("ConnectAdmin.Services.TemplateService", TemplateService);
}
with my html being:
<div id="template-index">
<div class="row">
<div class="col-sm-12">
<div class="info-box">
<div class="info-box-title">
Templates
</div>
<div class="info-box-content" ng-controller="ConnectAdmin.Controllers.TemplateIndexController as templateCtrl">
<table class="table table-striped table-responsive">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
<tr class="tr-select" ng-click="templateCtrl.openTemplate(template.templateId)" ng-repeat="template in templateCtrl.templates.collection">
<td>{{template.templateId}}</td>
<td>{{template.name}}</td>
<td>{{template.description}}</td>
</tr>
</tbody>
</table>
<div id="template-index-loader" class="loader" ng-show="templateCtrl.processing"></div>
<div class="info-box-footnote" ng-hide="templateCtrl.templates.collection.length">
Displaying {{templateCtrl.templates.skipped + 1}} to {{templateCtrl.templates.set + templateCtrl.templates.skipped}} of {{templateCtrl.templates.total}}
</div>
<div class="info-box-footnote" ng-show="templateCtrl.message.length">
{{templateCtrl.message}}
</div>
</div>
</div>
</div>
</div>
I don't think its the http call as I get no update if I return a hardcoded object.
The alert in the success callback gives me a correct value.
Thanks
My hunch is that your scope is being changed in your success callback. Try using your controller scope you defined in your constructor like this
successCallback(data: TemplateCollection) {
store.templates = { skipped: 0, set: 0, total: 0, collection: [] }
store.templates = data;
alert(store.templates.collection.length);
}
Otherwise I think when you say, "this" you're referring to the scope of the successCallback function
Ah great! Thanks, you put me on the right track.
Doing the update you said I was getting intellisense promts to say do you mean this.store which had the same outcome.
Following on from that and doing a bit of digging yes all the variables were undefined.
I've updated the Controller and Service to be:
module ConnectAdmin.Controllers {
import TemplateCollection = Interfaces.ITemplateCollection;
export interface ITemplateIndexScope extends ng.IScope {
vm: any;
}
export class TemplateIndexController {
static $inject = ["ConnectAdmin.Services.TemplateService"];
constructor(templateService: ConnectAdmin.Services.TemplateService) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] };
this.templateService = templateService;
this.take = 20;
this.skip = 0;
this.refresh();
}
refresh() {
this.processing = true;
this.templateService.index(this.take, this.skip, this);
}
successCallback(data: TemplateCollection) {
this.templates = data;
alert(this.templates.collection.length);
this.processing = false;
}
errorCallback(response: any) {
this.templates = { skipped: 0, set: 0, total: 0, collection: [] };
alert(response.status);
this.message = "An Error Occurred Contacting the API";
this.processing = false;
}
processing: boolean;
templates: TemplateCollection;
take: number;
skip: number;
message: string;
templateService: Services.TemplateService;
}
angular.module("ConnectAdmin").controller("ConnectAdmin.Controllers.TemplateIndexController", TemplateIndexController);
}
module ConnectAdmin.Services {
import TemplateCollection = Interfaces.ITemplateCollection;
import TemplateIndexController = Controllers.TemplateIndexController;
export class TemplateService {
constructor($http: ng.IHttpService) {
this.http = $http;
}
http: ng.IHttpService;
index(take: number, skip: number, templateController: TemplateIndexController) {
const req = {
method: "GET",
url: "https://localhost:44336/api/Templates?take=" + take + "&skip=" + skip,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
this.http(req).then(response => {
var data = response.data as TemplateCollection;
templateController.successCallback(data);
},
response => {
templateController.errorCallback(response);
});
}
}
angular.module("ConnectAdmin").service("ConnectAdmin.Services.TemplateService", TemplateService);
}
So I'm passing the instance of the controller into the service rather than the callback functions.
Cheers

Getting 404 while sending data from controller.js to spring controller

I have to send id to spring controller but I am getting 404. I am using angularjs, spring and mongodb.I am getting data perfectly. Onclick of approve/reject button id is being passed to controller.js but after that I am getting 404.
Also I have to pass index of row to controller so that i can remove row once data is updated in database. How to do this? Please provide some logic.
Html
<tbody>
<tr ng-repeat="task in taskDetails">
<td style="text-align: center;">{{task.name}}</td>
<!-- <td style="text-align: center;">{{task.owners}}</td> -->
<td style="text-align: center;">
<span ng-repeat="owner in task.owners">{{owner.ownerName.name}}{{$last ? '' : ', '}}</span>
</td>
<td style="text-align:center;">
<button class="btn btn-mini btn-primary" ng-click="approveTask(task)" value="approveTask">Approve</button>
<button class="btn btn-mini btn-danger" ng-click="rejectTask(task)" value="rejectTask">Reject</button>
</td>
</tr>
</tbody>
Controller
//controller.js
$scope.approveTask = function(task) {
alert(task);
var dataObj = {
id : task.id
};
$http.post('/userNotification/task/approve', dataObj).success(function (data) {
alert("Approved! "+ data);
});
}
$scope.rejectTask = function(task) {
alert(task);
var dataObj = {
id : task.id
};
$http.post('/userNotification/task/reject'+ dataObj).success(function(data) {
alert("Rejected! "+ data);
});
}
Spring Controller
//spring controller
package com.rmtool.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rmtool.mongo.dao.TaskDAO;
import com.rmtool.service.MongoService;
#Controller
#RequestMapping("/userNotification")
public class UserNotificationController {
#Autowired
MongoService mongoService;
#RequestMapping(value = "/fetchTaskForApproval",
method = RequestMethod.GET)
public #ResponseBody List<TaskDAO> notification(){
System.out.println("entering notification");
List<TaskDAO> taskDAOLists=new ArrayList<TaskDAO>();
taskDAOLists = mongoService.fetchPendingTask("Pending Approval");
System.out.println("exiting notification");
System.out.println(taskDAOLists);
return taskDAOLists;
}
#RequestMapping(value = "/task/approve", method = RequestMethod.POST)
public #ResponseBody void approveTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.approvePendingTask(task.getId());
}
#RequestMapping(value = "/task/reject/{id}", method = RequestMethod.POST)
public #ResponseBody void rejectTask(#PathVariable("id") String id){
mongoService.rejectPendingTask(id);
}
}
This is working fine...
//controller.js
$scope.approveTask = function($index,$task) {
$scope.currentIndex = $index;
//alert($task+$scope.currentIndex);
var dataObj = {
id : $task.id
};
$http.post('userNotification/approve',dataObj).success(function (data) {
alert("Approved! ");
$scope.taskDetails.splice($scope.currentIndex, 1);
$scope.currentIndex = -1;
});
}
$scope.rejectTask = function($index,$task) {
$scope.currentIndex = $index;
//alert($task+$scope.currentIndex);
var dataObj = {
id : $task.id
};
$http.post('userNotification/reject', dataObj).success(function(data) {
alert("Rejected! ");
$scope.taskDetails.splice($scope.currentIndex, 1);
$scope.currentIndex = -1;
});
}
//SpringController
#RequestMapping(value = "/approve", method = RequestMethod.POST)
public #ResponseBody void approveTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.approvePendingTask(task.getId());
}
#RequestMapping(value = "/reject", method = RequestMethod.POST)
public #ResponseBody void rejectTask(#RequestBody TaskDAO task){
System.out.println("task Id :"+task.getId());
mongoService.rejectPendingTask(task.getId());
}

Resources