簡體   English   中英

如何解決這個 Angular 路由問題?

[英]How can I fix this Angular routing problem?

我需要在我的 Angular 前端中使用 JavaScript 方法。

我用這種方式寫了一種 controller:

import * as commands from 'commands.js'

const http=require('http')
const post = (request) => {  return new Promise((resolve, reject) => {
    if(request.method === 'POST'){
      if(request.url === '/clean'){
        commands.clean();
      }
    }
  });
};
const server=http.createServer((req,res) => {
  post(req).then(body => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(body, null, 2));
  }).catch(err => {
    res.writeHead(403, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({msg: 'Invalid request'}, null, 2));
  });
});
server.listen(3000);

接下來使用ng generate service home我在其中編寫了一個服務:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class HomeService {
  private url = "http://localhost:3000";
  private httpHeader=new HttpHeaders({'Access-Control-Allow-Origin':'*'})
  constructor(private http:HttpClient) { }

  public clear():Observable<any>{
    return this.http.post(this.url+"/clean",null,{
      headers:this.httpHeader,
      responseType:'text'
    })
  }
}

然后我嘗試在我的 home.component.ts 中使用我的 function clear() 並像這樣使用它:

import { Component, OnInit } from '@angular/core';
import {MatCheckboxChange} from "@angular/material/checkbox";
import {HomeService} from "../home.service";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  constructor(private  homeservice: HomeService) {
  }
  [...]
    async clean(){
    this.homeservice.clear()
    }
  [...]
}

但是此時我發現了一個問題:當我啟動我的應用程序時

服務

我的應用程序在 /src/home 中自動重定向,它向我顯示了在 home.component.html 中寫入的 html 代碼。 特別是我使用默認的 Angular 路由模塊執行此操作。 在我的 app-roting.module.ts 中,代碼是:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {HomeComponent} from "./home/home.component";
import {SettingsComponent} from "./settings/settings.component";

const routes: Routes = [
  {path: 'home', component: HomeComponent},
  {path: 'settings', component: SettingsComponent},
  {path: '', redirectTo: 'home', pathMatch: 'full'
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}
export const routingComponents = [HomeComponent, SettingsComponent] 

它工作得很好,但是當我在 home.component.ts 的構造器中添加private homeservice: HomeService時,我的應用程序開始向我顯示 app.component.html 白頁,我什么也做不了。 如何解決此路由問題?

我想你不見了

<router-outlet></router-outlet> 

在你的 app.component.html

我發現了問題,我錯過了從@angular/common/http 導入app.module.ts HttpClientModule。 現在它起作用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM