ionic error while getting data from woocommerece api - angularjs

I am not able to spot what I am doing wrong. I have installed the woocommerce node package, and i have checked the rest api with the help postman app.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
WooCommerce: any;
constructor(public navCtrl: NavController) {
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
consumerSecret: cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
});
this.WooCommerce.getAsync("products").then((data)=>{
console.log(data);
}, (err)=>{
console.log(err)
})
}
}
Screenshot of the error:

Change
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
consumerSecret: cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
});
to
this.WooCommerce = WC({
url: "http://localhost/wordpress",
consumerKey: "ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
Notice the quotes.

Related

Can’t connect Express.js server to the Angular frontend

I created a Node.js application and also an Angular application. I need to get data from the database and also store data to the database. I'm having problems connecting my Express.js server to the Angular application.
File user.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { User } from '../User';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { BASE_URL } from '../const/config';
import { MONGO_EXPRESS_URL } from '../const/config';
#Injectable({
providedIn: 'root',
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(`${MONGO_EXPRESS_URL}/fetchdata`);
}
}
File users.component.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from 'src/app/services/user.service';
import { User } from '../../User';
#Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
users: User[] = [];
constructor(private userService: UserService) {}
ngOnInit(): void {
this.userService.getUsers().subscribe((users) => (this.users = users));
}
}
This error pops up when I run the Angular application:
File server.js
app.use("/", router);
app.listen(port, function () {
console.log("Server is running on Port: " + port);
});
router.route("/fetchdata").get(function (req, res) {
users.find({}, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
});
The problem is the route: https://localhost:4000.
It would be http://localhost:4000 (http:// instead of https://).
It should kind of look like this on your Node.js. You should set up the Express.js server like so:
constructor() {
this.app = express()
}
Initialize{
this.app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT');
if('OPTIONS' === req.method){
res.sendStatus(200);
}
else {
next();
}
})
this.app.use(RouterWebservices)
this.app.listen(your.HttpPort, your.Ip, () => {
console.log('Server now listening at ', your.HttpPort, 'IP ', your.Ip);
})
}
Then you need to declare your variables in a router.webservice.ts file:
export const RouterWebservices = express.Router()
RouterWebservices.get('/fetchdata', FetchWebservice)
And write a FetchWebserivce where you simply answer the request with data.

integrated angularjs service

hello every one I had a problem, I create my Ticketservice. this file and I try to add it to the home.ts file but it gives me an error
tickerServices.ts
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root',
})
export class TicketService{
result:any;
constructor(public http: HttpClient) { }
getTicket(){
var CronJob = require('cron').CronJob;
var id=this.formulaire.id;
new CronJob('* * * * * *', function(){
const http = require('http');
console.log('You will see this message every second');
/* this.url+'/'*/
http.get('http://localhost:8888/'+id+'/notif', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
this.resulta=data;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}, null, true, 'America/Los_Angeles');
}
}
home.ts
import {Component} from "#angular/core";
import {NavController, PopoverController,NavParams} from "ionic-angular";
import { HttpClient } from '#angular/common/http';
import { TicketService } from '../services/ticketservice'
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public search = {
date: new Date().toISOString()
}
constructor(public nav: NavController,public http: HttpClient,public popoverCtrl: PopoverController ,public tikSer:TicketService) {
}}
when I test it, he gives me undefined ".. /services/ticketservice"
Add it like this
import { TicketService } from '../../services/ticketservice'

process.nextTick is not a function at new MicrophoneStream (microphone-stream.js:114) at recognizeMicrophone (recognize-microphone.js:107)

I am getting token in frontend from the backend .I am getting the error at var stream = recognisationMicrophone() .From there it is going in catch section.
i have tried https://github.com/watson-developer-cloud/speech-javascript-sdk/issues/103#issuecomment-479593656
import { Component, OnInit } from '#angular/core';
import recognizeMicrophone from 'watson-speech/speech-to-text/recognize-microphone'
#Component({
selector: 'app-bot',
templateUrl: './bot.component.html',
styleUrls: ['./bot.component.css']
})
export class BotComponent implements OnInit {
constructor() { }
ngOnInit() {
}
onListenClick() {
fetch('https://652443a9.ngrok.io/api/speech-to-text/token')
.then(function(response) {
return response.text();
}).then(function (token) {
console.log('token',token)
var stream = recognizeMicrophone({
token: token, // use `access_token` as the parameter name if using an RC service
objectMode: true, // send objects instead of text
extractResults: true, // convert {results: [{alternatives:[...]}], result_index: 0} to {alternatives: [...], index: 0}
format: true // optional - performs basic formatting on the results such as capitals an periods
});
stream.on('data', function(data) {
console.log("1111111")
console.log(data);
});
stream.on('error', function(err) {
console.log("2222222")
console.log(err);
});
}).catch(function(error) {
console.log("3333333333333")
console.log(error);
});
}
}

How to use Sql server connection in angular 6?

I have do connection in 'Angular6' using sqlserver.
server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'abc',
password: 'abc',
server: 'servername',
database: 'xyz'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from tbl', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
data.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
getUser(userId) {
return this.http.get('https://jsonplaceholder.typicode.com/users/'+userId)
}
getPosts() {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
}
getPhotos()
{
return this.http.get('https://jsonplaceholder.typicode.com/photos');
}
getTodos()
{
return this.http.get('https://jsonplaceholder.typicode.com/todos');
}
}
Right now I have used dummy API'S for result.
how to get my database results in service?
I have successfully get result from Sqlserver database.
I also want to display record in my Component
user.component.html
<h1>Users</h1>
Can I have to import server.js in user.component.ts.
If yes than how can I do that?
I think you are misunderstanding angular. Angular run into browser and its context is limited to that.
If you need to connect to a database, you need to use some backend technologies, like express and nodejs, as the code you posted.
The main way is to expose some backend services, like REST services, developed with a server side techonology (nodejs, j2ee, php, etc) and then use Angular to ask them for data.
Generally to achieve this goal in angular you should use HttpClient
You should search for a tutorial, like this
Angular example to request data
In angular you should create a service class to call your exposed service, then into that class you could create a method like this:
import {HttpClient, HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs';
import {Injectable} from '#angular/core';
import {catchError, map, tap} from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class TestService {
get(): Observable<any> {
return this.http.get([YOUR_BACKEND_SERVICE_URL]).pipe(
catchError(this.handleError(`get`))
);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
this.log(`${operation} failed: ${error.message}`);
return of(result as T);
};
}
}
Then you should write a component like this:
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
data: any;
constructor(private testService: TestService) { }
ngOnInit() {
this.getData();
}
getData(): void {
this.testService.get().subscribe(data => console.log(data));
}
}
You need to create service and component with AngularCli in order to avoid to manually declare and import them into app.module.ts
For a better understanding of what is happening I suggest you to read Angular Tour of Heroes tutorial, Services section

angular-meteor.auth resolve to a blank page

I'm trying to authenticate the user before the view, in this case dashboard, gets rendered.
If the user is logged in, then your good to go, but if not, redirect to login state.
This is my controller:
import angular from 'angular';
import angularMeteor from 'angular-meteor';
import uiRouter from 'angular-ui-router';
import angularMeteorAuth from 'angular-meteor-auth';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { name as navBar } from '../navBar/navBar';
import './dashboard.html';
class dashboardCtrl {
constructor($scope) {
'ngInject';
if (Meteor.user()) {
console.log('logged in ', Meteor.user());
} else {
console.log('not logged in or error');
}
}
}
const name = 'dashboard';
export default angular.module(name, [
angularMeteor,
uiRouter,
navBar,
angularMeteorAuth
])
.component(name, {
templateUrl: `imports/ui/components/${name}/${name}.html`,
controller: dashboardCtrl,
})
.config(function($stateProvider, $urlRouterProvider) {
'ngInject';
$stateProvider
.state('dashboard', {
url: '/dashboard',
template: '<dashboard></dashboard>',
resolve: {
user: function($auth, $state){
return $auth.requireUser().then(function(){
return true;
}, function(err){
$state.go('login');
});
}
}
})
})
This works fine if the user is not logged in, it will redirect to login normally, but when the user is indeed logged in and you try to refresh in dashboard it returns a blank screen/page with no console logs or errors or anything.
How can I solve this?
Thanks!

Resources