I'm trying to call custom API in angular but for some reason it doesn't call it. Before this I made 10 functions in angular (in _api.service.ts) that call web API in the same way and they are correct, my web API is called and data is returned, everything is good. Then I made one more method in web API and one more component in angular (function getList() is called in it), and it didn't work, API is never called.
getList(id: string, chosen: string): Observable<StopListModel[]> {
let myUrl: string = API_URL + '/stop/list';
myUrl += '/' + id;
myUrl += '/' + chosen;
//debugger goes to this line, url is correct but API not called
return this.http.get<StopListModel[]>(myUrl, this.httpUtils.getHTTPHeader());
}
When I was debugging I saw that url for API is correctly sent from angular, like in 10 other functions that successfully call API in my project, so I think I don't need to send you code from my web API. I was confused so I moved line that is calling the getList() from new component to existing component, where I already know my _api.service will successfully call web API because in that component there is a function (for example getUsers() ) that correctly calls API. And it didn't work, API is not called for getList().
I assumed there is something wrong with web API for getList(), but just to be sure in that second component I called another _api.service function (that works when called from another component), and surprisingly - API was not called for that function either.
Then I saw what I think the problem is: when I try to call any function in any of my components, all this "new" functions never call API, just the old ones that have already been there, even though they correctly work in their own components.
export class DetaljiStopoviComponent{
stops$: Observable<StopStatisticsModel[]>;
list$: Observable<StopListModel[]>
constructor(
private apiService: APIService,
route: ActivatedRoute
) {
var id = route.snapshot.params['id'];
this.stops$ = this.apiService.getStopStatistics(id); //this works, it was there before - but any other calling I add under this, API is not called (this is the case for every component, every function)
this.list$ = this.apiService.getList(id, '3'); //this is the newest one, I can't make it call API even in the empty components
}
}
I am so confused and not experienced in angular, I'm very courious what the problem is. I don't think something is wrong with web API, but I'm not sure. Does anyone have suggestion?
I believe it is a syntax issue, for get method try this
return this.http.get<StopListModel[]>(myUrl, {headers:this.httpUtils.getHTTPHeader()});
Looks like you are forgot to subscribe to:
this.stops$ = this.apiService.getStopStatistics(id);
this.list$ = this.apiService.getList(id, '3');
I think this.stops$ works for you because somewhere in the template you have async pipe(stops$ | async).
So try to do:
this.list$.subscribe(response => console.log(response));
after that request should sent
Related
I'm used to using Express with a templating engine, like Handlebars. I want to start working with Svelte and SvelteKit, but I'm unsure how to start working with both. I am stuck on passing data to the frontend from the server. In Express, I'd normally connect to the database, and then pass the data to res.render, where the templating engine would then take over. So far, I think I have to run a handle function to pass the data, and then I can access it from my page. But it seems that the handle function runs for every request, and if all my pages require different data, does that mean I have to use a giant switch statement or something for every page?
Can anybody tell me if that's the right way to pass data over, or if there's a better way. Sorry, I'm fairly new to metaf rameworks and Svelte.
There are two ways to achieve what you want to do.
Let for both cases assume you have an about page and want to show dynamic data on this page like some team members. You would have a file called about.svelte (this makes the /about route) with in it something like:
<script>
export let team = [];
</script>
{#each team as member}
...
{/each}
Now how to get the team data to the page itself ?
the load function
The first option is the load function, this is a function that runs before the page is loaded and can be used to fetch data for this page. You would put the following block in about.svelte, usually before the other script block:
<script context="module">
export async function load({ fetch }) {
const team = await fetch('/api/team').then(res => res.json());
return {
props: {
team
}
}
}
</script>
Important to note with this one is that you need some sort of api (/api/team in this case) that can give you the data.
a page endpoint
The second option is to make a so called page endpoint this acts as a kind of api and lives next to the page itself. In the same folder as about.svelte add a file about.js:
export async function get() {
const team = []; // add team data here somehow
return {
status: 200,
body: {
team
}
}
what's the difference ?
When to use which approach is mostly up to you, but you have to remember the following two things:
The load function will likely need another api somewhere (this does not have to be SvelteKit)
The load function is, on the first page, executed on the server and afterwards will always run on the client. The endpoint on the other hand always runs serverside.
We have a requirement that we'd like to develop a "mini" testing framework for use within our Angular application. The point of the framework is to be able to manipulate API calls to alter the response body and status code in order to trip various error handlers within our application and make sure the application is responding correctly to errored API calls.
To do this I have been researching how to call Angular services from outside of Angular. This article describes how it is possible to create a service and then trigger it from outside Angular by calling the window.fireAngularEvent('sampleEventName', args) function.
However when I tried to do this via the browser, I get the following: Uncaught TypeError: window.fireAngularEvent is not a function
Here is my Angular service
export class GlobalApiTestingFrameworkService {
constructor() {
window['fireAngularEvent'] = (eventName, args) => {
console.log('fireAngularEvent : ' + eventName + ' : ' + args);
}
}
}
What do I need to do to be able to call the window.fireAngularEvent function? Do I need to define it outside of Angular within its own JS file? If so, what exactly do I include within the function body to allow it to communicate with the service? The article I linked isn't very clear.
The problem is due to the space in window['fireAngularEvent '] replace the defintion with window['fireAngularEvent'] and you'll be able to call window.fireAngularEvent without any issue.
Make sure that your service is instantiated at least one time.
To be sure You can use for example your service in AppComponent like that:
export class AppComponent {
constructor(private globalApiTestingFrameworkService: GlobalApiTestingFrameworkService){
}
}
I am in the process of moving from using http to using socket.io to bring data into to my Angular 2 app. In the example I'd like help with I am using a private version of the api.service in my component constructor. All I need to do now is call the "get" function that's defined in the api.service (already set up to use socket.io). This is what the "get" function from the api.service looks like:
public get(req: string, options: any, callback: IRequestCallback) {
// go get stuff
}
Now in my component I had been using an http get function that looked like this:
getByCategory() {
return this._http.get(this._url)
.map((response:Response) => response.json())
.catch(this._errorsHandler);
}
Now I am change this to use the socket.io function from my api.service instead. As you can see in my code at the top, the socket "get" call from the api.service is asking for 3 parameters (a string, options, and a callback). I tried this:
getByCategory() {
return this.__socket.get(this._url, this.args, function(data) {
});
}
... but now I realize the URL is already being provided in the api.service. So what's stumping me, as silly as this may sound, is what I can pass as the first parameter. I tried passing in an empty string as the first parameter, but that errored out. What string could I pass here, instead of the url? Or is there some other way around this?
First, I've had no issues with the Http module, so I'm curious why you made the switch (not that I know all of the use cases!)
That being said, it sounds like it really depends on how socket.io is handling the underlying code -- optional parameters in Typescript ("optional") normally expect undefined as a placeholder, so you could try passing undefined in this case.
I am trying to build a basic rpg like simple web game. I have a java server that provides a rest api to a pure html5 application.
This application has a service that returns quests by category. It also allows the user to view details about the quest. The quests are given through a rest api. I am reading this api using the $resource dependency.
The problem is, I have a service that is defined like this:
(function( ng, app ) {
"use strict";
// I provide a repository for the quests.
app.service(
"questService",
function( $q, $resource, $http, _, categoryService ) {
var QuestbookAPI = $resource( 'http://174.126.249.6\\:8080/worldcraft/quests' , {}, { query: {method: 'GET', isArray: true} });
var quests = [];
QuestbookAPI.query(function(newQuests){
console.log("I ran !!!!! WOOTZORS . I am the questbook api query.");
quests = newQuests;
_.each(quests, function(quest){
quest.id = quest.questID.id;
quest.categoryID = quest.questCategory.id;
});
});
// ***** general questbook api
function getQuestByID( id ){}
function getQuestsByCategory( categoryId ){}
....
// ***** end general questbook api
// I get the quest with the given ID.
// Return the public API.
return({
getQuestByID: getQuestByID,
getQuestsByCategoryID: getQuestsByCategoryID,
getRandomQuestExcluding: getRandomQuestExcluding,
});
}
);
})( angular, Worldcraft );
for some reason, when the controller using this service calls for getQuestsByCategoryID, the resource query does not run.
If I leave the page and revisit it, the query runs and the quests array is populated how I expected it.
My question is, why isn't my query running before anything else? I feel like I am missing a very fundamental concept.
the git for the project is on github at
https://github.com/ClinkWorks/Worldcraft-UI
the running project is at
http://www.clinkworks.com/worldcraft-ui
If you click quests, and then combat, go back a level, and hit combat again you can see what I mean.
For some reason the getQuestsByCategoryID function is running way before QuestbookAPI.query() even though the query is ran right when the service is declared... I am pretty confused..
I know its something to do with promises... or the $q object, but i'm not quite sure how.
$resource.query calls are all asynchronously filled. There's no guarantee the call will execute before all your other code runs.
Your caller should be the one running the callback inside query & setting it to a $scope variable. You can then use a $watch to check for the assignment & do something after the data has arrived.
I am using meteorjs and there are so called publications and meteor methods. Inside of these you can access a variable this.connection that holds information about all the http headers and connection you have with the specific user, for example the hostname over which they got access to your site.
As I want to make my application multidomain like slack, I now need to hook the database methods to limit the returned dataset to the right hostname.
Problem: This data is only available inside of the poblication or meteor method.
Is there any way to get the this of the calling method without changing the signatures of all my model functions?
Example:
mySpecialMethodWhereThisIsRight = function(param1) {
console.log(this.connection.httpHeaders.host) //Prints out the servername
modelname.mySelfMadeFunction(someData);
}
modelname = {
mySelfMadeFunction: function (data) {
console.log(this.connection.httpHeaders.host) //prints nothing
# some voodo
console.log(this.connection.httpHeaders.host) //Prints out the hostname
}
}
I am now looking for that "voodo" otherwise I would have to rewrite a lot of functions and the places they are called. (not that easy as there is no refactoring tool for coffeescript that actually works reliably)
Not sure I understood, but if you're able to make changes to the calling methods, would this work for you?
mySpecialMethodWhereThisIsRight = function(param1) {
console.log(this.connection.httpHeaders.host) //Prints out the servername
modelname.mySelfMadeFunction.bind(this)(someData);
}