繁体   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