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'
Related
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.
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);
});
}
}
Array not passing from service to component:
In the test() function on the service.ts page, google calendar data is successfully being read and pushed to an array called response. All the data logs.
When lesson-summary.component.ts calls on the test() function, the response array data does not show up in the lesson-summary.component.html
Thanks for any help!
google-calendar.service.ts
import { Injectable, Directive } from "#angular/core";
import * as moment from "moment-timezone";
declare var gapi: any;
#Injectable({
providedIn: "root"
})
export class GoogleCalendarService {
private response = [];
constructor() { }
test() {
gapi.load("client", () => {
gapi.client.init({
apiKey: "API string here",
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
}).then(() => {
var month = moment().month();
const firstOfMonth = moment().startOf("month").format("YYYY-MM-DD hh:mm");
const lastOfMonth = moment().endOf("month").format("YYYY-MM-DD hh:mm");
var firstOfMonthUTC = moment.tz(firstOfMonth, "America/Toronto").format();
var lastOfMonthUTC = moment.tz(lastOfMonth, "America/Toronto").format();
return gapi.client.calendar.events.list({
calendarId: "calendar id here",
timeMax: lastOfMonthUTC,
timeMin: firstOfMonthUTC,
singleEvents: true
});
})//end of .then
.then((data) => {
this.response.push.apply(this.response, data.result.items);
console.log(data.result.items, "data.result.items");
return this.response;
});//end of .then
});//end of .load
}//end of test
}//end of export
lesson-summary.component.ts
import { Component, OnInit } from "#angular/core";
import { Observable } from "rxjs";
import { GoogleCalendarService } from "../google-calendar.service";
declare var gapi: any;
#Component({
selector: "app-lesson-summary",
templateUrl: "./lesson-summary.component.html",
styleUrls: ["./lesson-summary.component.css"]
})
export class LessonSummaryComponent implements OnInit {
private response;
constructor(
private calendarService: GoogleCalendarService) {
this.response = this.calendarService.test();
}
ngOnInit() {
}
}
lesson-summary.component.html
<ul>
<li *ngFor = "let item of response">
{{ item.summary }}
</li>
</ul>
That's because you're mixing promises and sync functions in an incorrect way, so the test() function will not return anything.
Try adding a promise to your test():
test() {
return new Promise(resolve => { // <-- now test func return promise
gapi.load("client", () => {
gapi.client.init({
apiKey: "API string here",
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
}).then(() => {
// code...
}).then((data) => {
// code...
resolve(this.response); // <-- when we have the response, we are resolving the promise
});
});
});
}
And then use this promise in the component:
this.calendarService.test().then(data => this.response = data);
Learn more about promises on MDN
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.
I'm fairly new to AngularJS (2.0.0-beta.16). I've managed to setup a service that pulls data from an API, via a GET request. Now, how do I set it up to run the GET request every n seconds? I've seen other posts saying you could just using this._http.get(...).interval(5000).map(...);, however when I've tried that, I get a Typescript compilation error:
Property 'interval' does not exist on type 'Observable'.
Am I making a silly mistake or is there a better pattern for doing this?
import { Injectable } from 'angular2/core';
import { Http, Response } from "angular2/http";
import { Observable } from "rxjs/Observable";
import * as _ from "js/lodash.js";
import { Foo } from "./foo";
#Injectable()
export class FooService {
fooList: Observable<Foo[]>;
constructor(private _http: Http) {
this.fooList = this._http.get('http://localhost:9090/api/').map(
response => {
var json = response.json();
if(response.ok === true) {
let newFooList: Foo[] = [];
_.forEach(json, f => {
newFooList.push(new Foo(f));
});
return newFooList;
}
throw Error("Bad status: " + response);
});
}
}
This is probably not the only (or the best) way, but it worked for me. The only issue is that the first GET request is delayed by the amount of time specified by create().
import { Injectable } from "angular2/core";
import { Http, Response } from "angular2/http";
import { Observable } from "rxjs/Observable";
import { IntervalObservable } from "rxjs/observable/IntervalObservable";
import * as _ from "js/lodash.js";
import { API_URI } from "./constants";
import { Foo } from "./foo";
#Injectable()
export class FooService {
public fooList: Observable<Foo[]>;
constructor(private _http: Http) {
this.fooList = IntervalObservable.create(2000).flatMap(
() => {
return this._http.get(API_URI);
}).map(
response => {
var json = response.json();
if(response.ok === true) {
let newFooList: Foo[] = [];
_.forEach(json, f => {
newFooList.push(new Foo(f));
});
return newFooList;
}
throw Error("Bad status: " + response);
});
}
}