Home > Net >  For which reason this Angular Service is not working?
For which reason this Angular Service is not working?

Time:02-12

I created an Angular app with controller. I can successfully use the controller (with Postman, see screenshot below).

At the fronted I implemented a new component including service to show the data from controller (see code below). The service is not working. No data are shown at the application.

I made a breakpoint in feedback.service.ts/getFeedbacks() and in feedback.component.ts/ngOnInit(). Both are reached.

I mad a breakpoint at my controller and this one is never reached (except using postman).

Why doesn't the data from the controller reach the GUI?

enter image description here

feedback.component.html:

<div style="margin: 35px;">
   <h1>Feedback List:</h1>
   <div *ngFor="let feedback of feedbacks">
       {{feedback.comment}}
   </div>
 
   <h2>Count: {{feedbacks.length}}</h2>
</div>

feedback.component.ts:

import { Component, OnInit } from '@angular/core';
import { Feedback } from './feedback';
import { FeedbackService } from './feedback.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  feedbacks: Feedback[] = [];
    objects: any;

  constructor(private feedbackService: FeedbackService) { }

  ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);
  }
}

feedback.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback } from './feedback';

@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>('/feedback');
    return result;
  }
}

feedback.ts:

export interface Feedback {
    id:      number;
    comment: string;
    userId:  number;
}

app.modules.ts:

// other imports ...
import { FeedbackComponent } from './feedback/feedback.component';
import { FeedbackService } from './feedback/feedback.service';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    FeedbackComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: FeedbackComponent, pathMatch: 'full' }
    ]),
    BrowserAnimationsModule,
    MatToolbarModule
  ],
  providers: [FeedbackService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Screenshot from browser: enter image description here

CodePudding user response:

Configure so that Angular hits the correct url andport localhost:5235/feedback. Using developer tools and inspecting network tab you can find your GET request and have look if it's heading to the right direction. Easies way would be to use Angular's enviourment files and change the baseUrl.

https://stackoverflow.com/a/46532683/15439733

Then after that make sure CORS is enabled on your backend so Angular from another url localhost:44477 can access that endpoint.

https://www.freakyjolly.com/angular-proxy-configuration-to-handle-cors-issue/

CodePudding user response:

In your component.ts change this.

ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => {
          this.feedbacks.push(...feedbacks);
    })
}

Change this in your service.ts

getFeedbacks(): Observable<Feedback[]> {
    return this.http.get<Feedback[]>('http://localhost:444477/feedback');
}

let me know if it worked

CodePudding user response:

I changed the path to https://localhost:7235/feedback and now the breakpoint at the controller is reached.

launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51641",
      "sslPort": 44377
    }
  },
  "profiles": {
    "Test3": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7235;http://localhost:5235",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }, // .....

package.json:

{
  "name": "test3",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "prestart": "node aspnetcore-https",
    "start": "run-script-os",
    "start:windows": "ng serve --port 44477 --ssl --ssl-cert %APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key",
    "start:default": "ng serve --port 44477 --ssl --ssl-cert $HOME/.aspnet/https/${npm_package_name}.pem --ssl-key $HOME/.aspnet/https/${npm_package_name}.key",
    "build": "ng build",
    "build:ssr": "ng run Test3:server:dev",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },//...

app.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>https://localhost:44477</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup> // ...

CodePudding user response:

My solution:

at the .NET 6 backend, Program.cs add as first service:

builder.Services.AddCors(options => options.AddPolicy("TheCodeBuzzPolicy", builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
}));

then add after app.UseRouting():

app.UseCors("MyPolicy");
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("TheCodeBuzzPolicy");

});

  • Related