http.get Response object - can't access json()? - asp.net

I'm following this instructional video, Building web apps powered by Angular 2.x using Visual Studio 2017, and around 51:00 is the part I'm at and I'm hitting a problem in this source file:
https://github.com/CRANK211/vs17-ng2-dnc/blob/master/3%20-%20with-data/components/shared/account.service.ts#L18
With this function:
getAccountSummaries() {
return this.http.get('api/Bank/GetAccountSummaries')
.map(response => response.json() as AccountSummary[])
.toPromise();
}
I'm getting red text in Visual Studio on .json() which says
Symbol 'json' cannot be properly resolved, probably because it is located in inaccessible module
and when I try to run the application I get the exception message:
System.Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: No provider for AccountService!
Following the tutorial I used the same template as the instructor did but I think something must have changed since then since he has a single app.module.ts while my template came with four: app.module.client.ts, app.module.server.ts, and app.module.shared.ts and unfortunately as someone new to ASP.NET Core and Angular2 I have no idea why they're different or what the significance might be.
I've had success up to now by just making any changes he makes to his app.module.ts to my app.module.shared.ts which you can see here:
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { HeaderComponent } from './components/shared/header/header.component';
import { AccountListComponent } from './components/account/account-list/account-list.component';
import { AccountSummaryComponent } from './components/account/account-summary/account-summary.component';
import { AccountDetailComponent } from './components/account/account-detail/account-detail.component';
import { FormatAccountNumberPipe } from './components/shared/format-account-number.pipe';
import { AccountActivityComponent } from './components/account/acccount-activity/account-activity.component';
import { AccountService } from './components/shared/account.service';
export const sharedConfig: NgModule = {
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
NavMenuComponent,
CounterComponent,
FetchDataComponent,
HomeComponent,
HeaderComponent,
AccountListComponent,
AccountDetailComponent,
AccountSummaryComponent,
AccountActivityComponent,
FormatAccountNumberPipe
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'account', pathMatch: 'full' },
{ path: 'account', component: AccountListComponent },
{ path: 'detail/:id', component: AccountDetailComponent },
{ path: '**', redirectTo: 'account' }
])
],
providers: [ AccountService ]
};
Everything compiled fine and worked just like his until this .json() line unfortunately.
How do I fix it?

The red text you get from Visual Studio is probably because it VS cannot resolve the response object. The error should be gone when you prepend the following to your file
import { Response } from '#angular/http';
and change add the type Response to your map functions like so:
getAccountSummaries() {
return this.http.get('/api/Bank/GetAccountSummaries')
.map((response: Response) => response.json() as AccountSummary[])
.toPromise();
}
The other issue you have with the missing provider, is probably because the AccountService is used in a component, and this component is part of a module, and this module does not have the AccountService defined as a Provider. So make sure that every module you have has
providers:[ AccountService ]
defined in it's configuration.
hope that helps

Related

Storybook with Angular Couldn't find story matching 'story-title--task-name'

I try to work with Storybook in my Angular project, and I run into a misterious error message, and I have no clue what's happening here.
This is my tag.component.stories.ts file:
import { CommonModule } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule } from '#angular/router';
import { Meta, moduleMetadata, Story } from '#storybook/angular';
import { AppRoutingModule } from 'src/app/app-routing.module';
import { TagComponent } from './tag.component';
export default {
title: 'Attached Tags',
component: TagComponent,
decorators: [
moduleMetadata({
declarations: [TagComponent],
imports: [BrowserModule, CommonModule, RouterModule, AppRoutingModule]
})
]
} as Meta;
const Template: Story = (args) => ({
props: {
...args
}
});
export const GreenPost = Template.bind({});
GreenPost.args = {
tag: {
id: 1,
name: 'Test tag',
color: '#bada55',
type: 'Post'
}
};
I get this error message:
Couldn't find story matching 'attached-tags--green-post'.
- Are you sure a story with that id exists?
- Please check your stories field of your main.js config.
- Also check the browser console and terminal for error messages.
So, I'm pretty sure after reading the documentation's "Simple component" section I don't have any idea how or where should I need to define any id for stories.
Here is my .storybook/main.js:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions"
],
"framework": "#storybook/angular",
"core": {
"builder": "webpack5"
}
}
This is the factory default I think.
Also checked the browsers console, and nothing else, just the visible message twice.
Any idea how can I solve this issue?

got this error, Error: Cannot match any routes

import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { LmfinComponent } from '../app/lmfin/lmfin.component';
import { MfinComponent } from './mfin/mfin.component';
import { GenFunctionProvider } from './gen-function.module';
import {DetailpembayaranComponent } from './detailpembayaran/detailpembayaran.component';
const appRoutes:Routes = [ //removed export
{ //removed square bracket
path: '',
redirectTo: '/mfin',
pathMatch: 'full'
},{
path: 'list',
component: LmfinComponent
},{
path: 'mfin/:id',
component: MfinComponent
},{
path: 'detailpembayaran',
component: DetailpembayaranComponent
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(appRoutes, {useHash:true})
],
declarations: []
})
export class AppRoutingModule { }
i'm still new at routing, when i try to makes routing, i got this error
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
anyone can help me please?
You default path to redirect /mfin
You no path with /mfin you have URL /mfin/:id. This is not match with /mfin
So need to add route URL of /mfin.
Try this, As far as I understood you are missing some codes in index.html. Check whether you have below code in your index.html head section. If not add it and see.
<base href="/">
Also ensure your server has configured for HTML5 pushState like explained in Angular 2.0 router not working on reloading the browser
I hope this will resolve your problem. If you have any doubts or suggestion let me know.

Adding Dragular to Angular2 Application: document is not defined

I am fairly new to Angular2 and I am having issues adding Dragula to my application. When I run the application an error is thrown prior to loading the home page:
Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: document is not defined
The error message mentions Prerending which I suspect is in relation to the project using asp-prerender-module.
I've tried to follow official tutorials from Dragula and forum posts. Below are my app.module and component file snippets (... denotes summarised code):
app.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
...
import { SearchComponent } from './components/search/search.component';
import { BrowserModule } from '#angular/platform-browser';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { Injectable } from '#angular/core';
import { DragulaModule } from 'ng2-dragula';
#NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
...
SearchComponent
],
imports: [
UniversalModule,
BrowserModule,
FormsModule,
DragulaModule,
CommonModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
...
{ path: 'search', component: SearchComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModule {
}
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService, DragulaService]
})
I suspect I am missing an a step when including Dragula, but I cannot figure out where. I have included both dragula (^3.7.2) and ng2-dragula (^1.3.0) in my package.json file.
your DragulaService initialization is wrong!! check Dragula documentation link
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService]
})
expoert searchcomponent{
constructor(private dragulaService: DragulaService) {
console.log('DragulaService created');
}
}
Now you can play with drag and drop
If you want more control over drag and drop you can add events and options to dragulaService.
constructor(private dragulaService: DragulaService) {
dragulaService.drag.subscribe((value) => {
console.log(`drag: ${value[0]}`);
this.onDrag(value.slice(1));
});
dragulaService.drop.subscribe((value) => {
console.log(`drop: ${value[0]}`);
this.onDrop(value.slice(1));
});
dragulaService.over.subscribe((value) => {
console.log(`over: ${value[0]}`);
this.onOver(value.slice(1));
});
dragulaService.out.subscribe((value) => {
console.log(`out: ${value[0]}`);
this.onOut(value.slice(1));
});
}
private onDrag(args) {
let [e, el] = args;
// do something
}
private onDrop(args) {
let [e, el] = args;
// do something
}
private onOver(args) {
let [e, el, container] = args;
// do something
}
private onOut(args) {
let [e, el, container] = args;
// do something
}

Error while configuring routes in Angular 2

i have been working with a product list Project and while configuring routes to navigate between different views, I get a red squiggly under the '#Routes' decorator and when i hover over the Routes, it says 'Routes only refers to a type, but is being used as a value here'. I researched in so many sights including here and tried many different ways to resolve this but I could not find out the issue.
app.component.ts
import { Component } from '#angular/core';
import { ProductListComponent } from './products/product-list.Component';
import { ProductService } from './products/product.service'
import { Routes } from '#angular/router';
import 'rxjs/Rx'; // Load all features
import { WelcomeComponent } from './home/welcome.component'
#Component({
selector: 'pm-app',
template: `
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{pageTitle}}</a>
<ul class='nav navbar-nav'>
<li><a>Home</a></li>
<li><a>Product List</a></li>
</ul>
</div>
</nav>
</div>
` ,
entryComponents : [ProductListComponent],
providers: [ProductService]
})
#Routes([
{ path: '/welcome' , name: 'Welcome' , component: WelcomeComponent, useAsDefault: true},
{ path: '/products' , name: 'Products' , component: ProductListComponent }
])
export class AppComponent {
pageTitle:string = 'Acme Product Management';
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ProductListComponent } from './products/product-list.Component';
import { HttpModule } from "#angular/http";
import { RouterModule } from '#angular/router'
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule,FormsModule,HttpModule,RouterModule],
declarations: [ AppComponent,ProductListComponent,ProductFilterPipe,StarComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
welcome.compnent.ts
import { Component } from '#angular/core';
#Component({
templateUrl: 'app/home/welcome.component.html'
})
export class WelcomeComponent {
public pageTitle: string = 'Welcome';
}
I think my coding is fine. But unable to get the expected result. Please Help!
Found out, the issue is... with RC5, Routes is an array of path's & is no more a Decorator, and you have to import 'RouterModule' instead of 'provideRouter'. While exporting you have to use 'RouterModule.forRoot'.
Also with RC5, we no longer specify the string name of the component while configuring routes instead we only specify the path & component only. And we no longer use the prefix '/' for the path. Also we no longer using useAsDefault instead we use redirectTo property to configure the default path.
I have used a separate module to do my route configurations instead of doing it in the root component as earlier. An updated version of my route configuration is given as below. Hope this will be helpful.
app.routes.ts
import { Routes, RouterModule } from '#angular/router';
import { ProductListComponent } from './products/product-list.Component';
import { WelcomeComponent } from './home/welcome.component'
import { ProductDetailComponent } from './products/product- detail.component';
const routes: Routes = [
{
path: 'welcome' ,
component: WelcomeComponent,
},
{
path: 'products' ,
component: ProductListComponent
},
{
path: 'product/:id' ,
component: ProductDetailComponent
},
{
path:'',
redirectTo:'/welcome',
pathMatch:'full'
},
];
export const routing = RouterModule.forRoot(routes);

Angular2.1 Cannot read property 'get' of undefined

So, I'm currently trying to send a HTTP request, I'm doing everything exactly like in official guide and it's wont work (as usual when you make deal with Angular2)
Here is my app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { PageComponent } from './modules/Affiliate/affiliate.component';
import { NotFoundComponent } from './not-found.component';
const routes: Routes =
[
{ path: 'page', component: PageComponent },
{ path: '404', component: NotFoundComponent },
{ path: '**', redirectTo: '404' }
];
#NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(routes),
HttpModule,
JsonpModule
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
And here is my service, where I'm trying to send a http request
import { Injectable } from '#angular/core';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class GridService {
constructor(private http: Http) { }
getTableRaws(url): Promise<any> {
return this.http.get(url)
.toPromise()
.then(response => response.json().data as any)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Any ideas, please
Following the docs, I guess you missed the data type for the url param:
getTableRaws(url: string): Promise<any> {
...
}
UPDATE:
You need to add GridService as a provider in app.module. Refer to this SO answer.
If you have made these changes then update your code in the question and also provide the contents of app.component here.
Here is the solution that works for me:
constructor(#Inject(Http) private http: Http) {}

Resources