如何在应用初始化时从后端API推送其他路由

时间:2019-03-21 09:56:11

标签: angular api angular-ui-router

我正在写类似CMS的内容。我有两个应用。用Django写的后端和角度7的SPA。在后端部分,我认为list-pagesretrieve-page

http://127.0.0.1:8000/pages-management/pages发送请求时,返回json并包含以下数据:

[
  {
    "id": 1,
    "title": "some title 1",
    "section": "section1",
    "urlKey": "some_title_1"
  },
    {
    "id": 2,
    "title": "some title 2",
    "section": "section2",
    "urlKey": "some_title_2"
  },
]

根据sendint请求发送至:

http://127.0.0.1:8000/pages-management/pages/some_title_1

它返回:

{
  "id": 1,
  "title": "some_title_1",
  "section": "section1",
  "urlKey": "some_title_1",
  "content": "<p>html content</p>"
}

我想实现什么?

我想在角度应用启动时从/pages-management/pages加载数据,并从中创建路由。

在第一次尝试中,我尝试在标头组件初始化期间添加这些路由:

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  currentUserEmail: string;
  pages: Page[];

  constructor(private authService: AuthService, private pageService: PageService, private router: Router) {
  }

  ngOnInit() {
    // TODO remove the property this.authService.currentUserEmail and export currentUserEmail from localstorage?
    this.currentUserEmail = this.authService.currentUserEmail;

    this.pageService.getPages().subscribe(data => {
      this.pages = data;
      const data = this.router.config.filter(value => value.path === 'children')[0].children;
      this.pages.forEach(item => {
        data.push({path: item.urlKey, component: PageComponent});
      });
    }, error1 => {
    });
  }
} 

  <div class="nav-item mr-2">

        <div class="row">
          <div class="col">
            <div ngbDropdown class="d-inline-block">
              <button class="btn btn-light" id="studentZoneDropDown" ngbDropdownToggle>
                Strefa Studenta
              </button>
              <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
                <button class="dropdown-item" [routerLink]="['strefa-studenta', page.urlKey]"
                        *ngFor="let page of pages">{{page.title}}</button>
              </div>
            </div>
          </div>
        </div>
      </div>

当我让应用加载并通过导航栏中的链接输入网址时,它几乎可以正常工作。问题是当我尝试直接通过浏览器链接http://localhost:4200/children/some_title_1输入URL时,它确实起作用。但是可以通过导航栏中的链接从http://localhost:4200导航到http://localhost:4200/children/some_title_1

问题是如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

如果要在应用程序启动时执行数据加载,则可以使用APP_INITIALIZER注入令牌:

@NgModule({
   ...
   providers: [
      {
          provide: APP_INITIALIZER,
          useFactory: initializeApplication,
          deps: [/* Add dependencies here */],
          multi: true
      }
   ]
})
export class AppModule {}

export function initializeApplication(/* Inject dependencies here */) {
    return () => {
        // TODO: send http request or execute promises.
    };
}

在此处查找更多信息:https://www.tektutorialshub.com/angular/angular-how-to-use-app-initializer/

希望有帮助。