从组件运行到服务时如何移动起作用的功能

时间:2019-04-15 05:40:12

标签: angular angular-services angular-httpclient

我重新写了这个问题,以便更好地获得有关如何解决问题的帮助。当我将代码保存在component.ts文件中并在html页面上显示时,一切工作都很好,但是当我尝试将其移至服务时,会出现错误并且没有动态显示。

component.ts

import { PagesService } from './../services/pages.service';
import { Page } from './../admin/pages/page.model';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SERVER_URL } from '../../../src/environments/environment';


@Component({
  selector: 'app-partner',
  templateUrl: './partner.page.html',
  styleUrls: ['./partner.page.scss'],
})
export class PartnerPage implements OnInit {
  public pageList: Array<Page> = Array<Page>();
  fileName: string = "partner";
  page: Page;
  constructor(private pgsService: PagesService, private http: HttpClient) {}

  GetPages() {
    this.http.get(`${SERVER_URL}api/pages`)
    .subscribe(res=>this.Success(res),res=>this.Error(res));
  }
  GetPage(fileName: string) {
      this.http.get(`${SERVER_URL}api/pageName/${fileName}`)
    .subscribe(res=>this.SuccessPage(res), res=>this.Error(res));
  }
  ngOnInit() {
    this.GetPages();
    this.GetPage(this.fileName);

  }
  Error(res) {
    console.log(res);
  }
 Success(res) {
   console.log(res);
   this.pageList = res;
   console.log("this.pageList",this.pageList);
 }
 SuccessPage(res) {
   this.page = res;
   console.log("this.page",this.page);
 }

}

partner.html

<ion-header>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
  </ion-header>
<ion-content padding>
  <ion-title>{{page?.title}}</ion-title>
  <div class="partner-wrap">
    <ion-text>
      <h1 class="partner-header">{{page?.heading}}</h1>
      <img src="../../assets/partnerupogo.png" alt="PartnerUp!">
        <div [innerHtml]='page?.content'></div>
    </ion-text>
  </div>
  <div>{{page?.footer}}</div>
</ion-content>

我建议的pages.service.ts

import { PagesService } from './../services/pages.service';
import { Page } from './../admin/pages/page.model';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SERVER_URL } from '../../../src/environments/environment';


@Component({
  selector: 'app-partner',
  templateUrl: './partner.page.html',
  styleUrls: ['./partner.page.scss'],
})
export class PartnerPage implements OnInit {

  public page: Page;
  fileName: string = "partner";
  constructor(public pgsService: PagesService, public http: HttpClient) {}

  ngOnInit() {
    this.pgsService.GetPage(this.fileName)
    .subscribe(res=>this.pgsService.SuccessPage(res),res=>this.pgsService.Error(res));
    this.page = this.pgsService.page;

  }

}

我尝试将功能复制到服务,并通过该服务运行事物,但是它没有用。这些功能将通过服务运行并通过console.log运行,但是我无法将数据传递给组件以在html中显示。

我在src / app / partner / partner.page.ts(21,6)中出现错误:错误TS2339:类型'void'上不存在属性'subscribe'。

我如何转换它以便起作用?

3 个答案:

答案 0 :(得分:0)

获取页面似乎是可观察的,因此您需要先订阅它

date_dt1 = datetime.strptime(date_str1, '%A, %B %d, %Y')

希望有帮助

答案 1 :(得分:0)

//代码是异步的 //获取所有页面->您变成诺言的服务

getPages() {
    return this.http
      .get<Page[]>(`${SERVER_URL}api/pages`)
      .pipe(
       map(pages => {
      //for each record in the results
          for (let page of pages) {
        //return an empty array if no links
            if (!page["links"]) {
              page["links"] = [];
          }
        }
        return pages;
      })
    )
  .toPromise();
}

//在您的组件listPages中;

ngOnInit() {
    this.getPages();
  }
async getPages() {
    try {
      this.listPages = await this.pagesService.getPages();
      console.log(this.listPages);
   } catch (error) {}

}

答案 2 :(得分:0)

哦!我终于做到了!

首先,我需要在http请求之前添加return,以便可以将其发送到组件。

GetPage(fileName: string) {
    return this.http.get(`${SERVER_URL}api/pageName/${fileName}`);
  }

然后我需要使用?使用字符串插值时,我在显示页面时没有出现很多错误。我在html中也有错字。

<ion-header>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
  </ion-header>
<ion-content padding>
  <ion-title>{{pgsService?.page?.title}}</ion-title>
  <div class="partner-wrap">
    <ion-text>
      <h1 class="partner-header">{{pgsService?.page?.heading}}</h1>
      <img src="../../assets/partnerupogo.png" alt="PartnerUp!">
        <div [innerHtml]='pgsService.page?.content'></div>
    </ion-text>
  </div>
  <div>{{pgsService?.page?.footer}}</div>
</ion-content>

现在,它终于可以用作服务了,并且没有错误!如果这不是最好的方法,我愿意回答可能被认为是正确方法的答案。