Angular4,将值从模板传递给组件?

时间:2017-04-19 17:24:51

标签: angular

我正在学习Angular 4,而且我遇到了绊脚石。

我有以下 app / content.component.ts 文件:

import { Component, Input, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { Content } from './content';

@Component({
    selector: 'app-content',
    templateUrl: './content.component.html'
})

export class ContentComponent implements OnInit {
    @Input() loadScripts: string;
    items: FirebaseListObservable<any[]>;
    constructor(af: AngularFire) {
        this.items = af.database.list('/pages', { 
            query: {
                orderByChild: 'sortOrder',
                limitToLast: 100
            }
        });
    }
    ngOnInit() {
        console.log(this.loadScripts);
    }
}

我有以下 app / content.component.html 文件:

<div id="content-{{item.$key}}"  *ngFor="let item of items | async | path : 'path'">
    <h2>{{item.title}}</h2>
    <div [innerHTML]="item.content | trustedHtml"></div>
</div>

&#34;项目&#34;是Firebase的结果集。我需要传递&#34; item.loadScripts&#34;的值。到 ContentComponent 类中的loadScripts变量。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以自己订阅observable(将其移至ngOnInit)。在订阅中,您可以设置this.items并迭代结果。由于此更改,您希望跟踪订阅并取消订阅销毁。

import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { Content } from './content';

@Component({
    selector: 'app-content',
    templateUrl: './content.component.html'
})

export class ContentComponent implements OnInit, OnDestroy {
    @Input() loadScripts: string;
    subscriptions: Array<any> = [];
    items: Array<any>;
    constructor(private af: AngularFire) {}
    ngOnInit() {
        this.subscriptions.push(
            this.af.database.list('/pages', { 
                    query: {
                        orderByChild: 'sortOrder',
                        limitToLast: 100
                    }
                }).subscribe((items) => {
                    this.items = items;
                    this.items.forEach((item) => {
                        // do something with each item.loadScripts
                    });
                });
            );
    }
    ngOnDestroy() {
     this.subscriptions.forEach(s => s.unsubscribe());
    }
}

确保从html中删除异步管道。

<div id="content-{{item.$key}}"  *ngFor="let item of items | path : 'path'">
    <h2>{{item.title}}</h2>
    <div [innerHTML]="item.content | trustedHtml"></div>
</div>

如果您总是想要应用过滤器,请将订阅内的代码更新为类似的内容(并从html中删除过滤器):

this.items = items
    .filter((item) => {
        return checkPathFilter(item);
    });

this.items.forEach((item) => {
    // do something with each item.loadScripts
});

如果您总是过滤到1个项目,那么您可以一起删除ngFor all并在订阅中执行此操作:

this.item = items
    .find((item) => {
        return checkPathFilter(item);
    });

this.loadScripts = item.loadScripts;

答案 1 :(得分:2)

您应该将当前位于构造函数中的代码移动到我认为的[2017-04-19 17:33:43,783] WARN (org.eclipse.jetty.servlet.ServletHandler:620) javax.servlet.ServletException: java.lang.IllegalArgumentException: "uriTemplate" parameter is null. at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:159) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:499) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.IllegalArgumentException: "uriTemplate" parameter is null. at org.glassfish.jersey.uri.internal.JerseyUriBuilder.uri(JerseyUriBuilder.java:189) at org.glassfish.jersey.uri.internal.JerseyUriBuilder.uri(JerseyUriBuilder.java:72) at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119) at org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource.completeOrForwardRequest(ConnectorsResource.java:246) at org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource.completeOrForwardRequest(ConnectorsResource.java:281) at org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource.restartTask(ConnectorsResource.java:213) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) ... 23 more [2017-04-19 17:33:43,784] WARN /connectors/my-connector/tasks/0/restart (org.eclipse.jetty.server.HttpChannel:384) java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:684) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:221) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:159) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:499) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) at java.lang.Thread.run(Thread.java:745) [2017-04-19 17:33:43,788] WARN Could not send response error 500: java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z (org.eclipse.jetty.server.HttpChannel:4 lines 3767-3832/3832 (END) 方法中。

由于firebase请求的内容已经返回到组件,因此您无需从模板中返回它们。您只需要在请求处理函数期间将从firebase返回的任何内容复制到onInit()变量中。但是,如果在每个项目上定义loadScripts,那么您的loadScripts类属性将需要是一个数组,而不仅仅是一个字符串:

loadScripts

但是,我有几个问题。你需要对loadScripts的每个值做什么?

如果您需要以不同方式处理每个this.items = af.database.list('/pages', { query: { orderByChild: 'sortOrder', limitToLast: 100 } }); this.items.subscribe(items => this.loadScripts=items); ,那么最好编写一个以item作为输入然后处理/呈现它的子组件。如果处理更简单,你可以在item上定义一个函数,它将一个项作为一个参数,然后返回你需要的任何值。